Download Control Structures in C#: While, For, and Switch Statements and more Slides C programming in PDF only on Docsity!
CS 112 Introduction to
Programming
Lecture #9:
More Control Structures
http://flint.cs.yale.edu/cs112/
Outline
r Admin. and review
r Loop statements
m while statement
m Nested control
m do/while statement
m for statement
r break and continue statements
Recap
r The while statement
r Some typical ways to write while loops
m Counter-based
m Sentinel-based
m Others: e.g., ReverseNumber.cs
while ( condition )
statement;
ReverseNumber
number reverse
Assume initial input is ā1234567ā. Above is the current state.
ReverseNumber
number reverse
lastDigit = number % 10 ;
reverse = reverse * 10 + lastDigit ;
number % 10 reverse = reverse * 10 + number / 10
ReverseNumber
number
reverse
while (number > 0)
lastDigit = number % 10 ;
reverse = reverse * 10 + lastDigit ;
number = number / 10;
Outline
r Admin. and review
r Loop statements
m while statement
Ćæ Nested control
m do/while statement
m for statement
r break and continue statements
Nested Control
r The insertion of one
control structure
inside another
m Loops with if
statements
Initialize passes to zero
Initialize failures to zero
Initialize student to one
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
Else
Add one to failures
Add one to student counter
Print the number of passes
Print the number of failures
If more than eight students passed
Print āRaise tuitionā
Example: Analysis.cs
Outline
Analysis.cs
1 // Analysis.cs 2 // Analysis of Examination Results. 3 4 using System; 5 6 class Analysis 7 { 8 static void Main( string[] args ) 9 { 10 int passes = 0, // number of passes 11 failures = 0, // number of failures 12 student = 1, // student counter 13 grade; // one exam grade 14 15 // process 10 students; counter-controlled loop 16 while ( student <= 10 ) 17 { 18 Console.Write( "Enter grade (0-100): " ); 19 grade = Int32.Parse( Console.ReadLine() ); 20 21 if ( result >= 60 ) 22 passes = passes + 1; 23 24 else 25 failures = failures + 1; 26 27 student = student + 1; 28 } 29
A while loop that will loop 10 times
A nested if statement that determines
which counter should be added to
If the grade >= 60
add one to passes
Else add one to failures
Keep track of the total number of students
Initialize both passes and failures to 0
Set the student count to 1
Outline
Analysis.cs
30 // termination phase 31 Console.WriteLine(); 32 Console.WriteLine( "Passed: " + passes ); 33 Console.WriteLine( "Failed: " + failures ); 34 35 if ( passes > 8 ) 36 Console.WriteLine( "Raise Tuition\n" ); 37 38 } // end of method Main 39 40 } // end of class Analysis
Display the results to the user
If the total number of passes was greater than
8 then also tell the user to raise the tuition
Outline
r Admin. and review
r Loop statements
m while statement
m Nested control
Ćæ do/while statement
m for statement
r break and continue statements
The do Statement
r The do statement has the following syntax:
do
statement ;
while ( condition );
Uses bothUses both
thethe dodo andand
while while
reserved reserved
wordswords
The statement is executed once initially, then the condition isThe statement is executed once initially, then the condition is evaluatedevaluated
The statement is repetitively executed until the condition becomThe statement is repetitively executed until the condition becomes falsees false
The for Statement: Example
counter++
Establish initial value
of control variable.
Determine if final
value of control
variable has been
reached.
counter <= 10
Console.WriteLine
( counter * 10 );
true
false
int counter = 1
Body of loop (this may be
multiple statements)
Increment the
control variable.
for (int counter = 1; counter <= 10; counter++)
Console.WriteLine (counter * 10);
// beginning of the next statement
The for Statement
r A for loop is equivalent to the following
while loop:
initialization ;
while ( condition )
statement ;
increment ;
The for Statement
r It is well suited for executing a specific
number of times that can be determined in
advance
m Increment/Decrement
⢠When incrementing
ā In most cases < or <= is used
⢠When decrementing
ā In most cases > or >= is used
r Example: ForCounter.cs
Outline
ForCounter.cs
Program Output
1 // ForCounter.cs 2 // Counter-controlled repetition with the for structure. 3 4 using System; 5 6 class ForCounter 7 { 8 static void Main( string[] args ) 9 { 10 // initialization, repetition condition and incrementing 11 // are all included in the for structure 12 for ( int counter = 1; counter <= 5; counter++ ) 13 Console.WriteLine( counter ); 14 } 15 }
This is where the counter variable
is initialized. It is set to 1.
The loop will continue until counter is
greater than five (it will stop once it
gets to six)
The counter is incremented
(1 is added to it)
Note: counter can only be used in the body of the for loop!
When the loop ends the variable expires! We will
discuss this issue later!
The flexibility of the for Statement
r Each expression in the header of a for loop is optional
m If the initialization is left out, no initialization is performed
m If the condition is left out, it is always considered to be true,
and therefore creates an infinite loop
m If the increment is left out, no increment operation is
performed
r Both semi-colons are always required in the for loop
header
for ( ; ; )
// do something
A Problem to Think About
How to print this?
xxxxxxxx
xxxxxxx
xxxxxx
xxxxx
xxxx
xxx
xx
x
What about this?
xxxxxxxxxxxxxxx
xxxxxxxxxxxxx
xxxxxxxxxxx
xxxxxxxxx
xxxxxxx
xxxxx
xxx
x
Outline
r Admin. and review
r Loop statements
m while statement
m Nested control
m do/while statement
¶ for statement
Ćæ break and continue statements
Statements break and continue
r Used to alter the flow of control
m The break statement
⢠Used to exit a loop early
m The continue statement
⢠Used to skip the rest of the statements in a loop and
restart at the first statement in the loop
r Programs can be completed without their
usage; use with caution.
Using Break: Loop-and-a-Half Idiom
Initialize total to zero
Initialize counter to zero
While (true)
Input next grade (possibly the sentinel)
If ( the user has entered the sentinel)
break ;
Add this grade into the running total
Add one to the grade counter
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
Else
Print āNo grades were enteredā
Initialize total to zero
Initialize counter to zero
Input the first grade (possibly the sentinel)
While (grade != sentinel)
Add this grade into the running total
Add one to the grade counter
Input next grad (possibly the sentinel)
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
Else
Print āNo grades were enteredā
Outline
BreakTester.cs
1 // BreakTester.cs 2 // Using the break statement in a for structure. 3 4 using System; 5 6 7 class BreakTester 8 { 9 static void Main( string[] args ) 10 { 11 string output = ""; 12 int count; 13 14 for ( count = 1; count <= 10; count++ ) 15 { 16 if ( count == 3 ) 17 break; // skip remaining code in loop 18 // if count == 3 19 20 output += count + " "; 21 22 } // end for loop 23 24 output += "\nBroke out of loop at count = " + count; 25 26 Console.WriteLine( output ); 28 29 } // end method Main 30 31 } // end class BreakTester
Prints the message!
A loop that starts at one, goes
to ten, and increments by one
If count = 3 then break out of the loop
Display the last value that the
counter was at before it broke
Outline
ContinueTester.cs
1 // ContinueTester.cs 2 // Using the continue statement in a for structure. 3 4 using System; 5 6 7 class ContinueTester 8 { 9 static void Main( string[] args ) 10 { 11 string output = ""; 12 13 for ( int count = 1; count <= 10; count++ ) 14 { 15 if ( count == 5 ) 16 continue; // skip remaining code in loop 17 // only if count == 5 18 19 output += count + " "; 20 } 21 22 output += "\nUsed continue to skip printing 5"; 23 24 Console.WriteLine( output ); 26 27 } // end method Main 28 29 } // end class ContinueTester
A loop that starts at 1, goes
to 10, and increments by 1If count = 5 then continue looping causing
the program to skip the rest of the loop
Prints the message.
The switch Statement
r The switch statement provides another
means to decide which statement to execute
next
r The switch statement evaluates an
expression, then attempts to match the result
to one of several possible cases
r Each case contains a value and a list of
statements
r The flow of control transfers to statement list
associated with the first value that matches