if-else, switch, while, for, do-while Control Statements
Conditional Statements <ul><li>So far statements of our programs execute sequentially one after another. </li></ul><ul><li...
Syntax <ul><ul><li>if ( < condition > )  </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li><s tatement_true_1> ; </l...
Another Syntax (without { }) <ul><ul><li>if (< condition >) </li></ul></ul><ul><ul><li><s tatement_true> ; </li></ul></ul>...
Flow diagram of if-else test condition true statements true next statement false false statements
if-else  example <ul><li>Write a program that inputs two integer numbers and displays the maximum one. </li></ul><ul><li>T...
Boolean type and expressions <ul><li>The condition in an if statement must be a Boolean expression (named for George Boole...
<ul><li>The  conditional operator  ( ?: ) can be used in place of an  if…else  statement. </li></ul><ul><li>Console.WriteL...
Relational Operators <ul><li>Relational operators are used to compare values:  </li></ul><ul><li>They take two operands </...
Logical operators <ul><li>Boolean expressions can be combined using logical operators: AND, OR, NOT </li></ul><ul><ul><li>...
Example <ul><li>Range check: between 0 and 100 (includes 0 and 100), or not?   </li></ul><ul><ul><li>If so, display a mess...
De Morgan’s Rules <ul><li>Compare solution 2 and 3 </li></ul><ul><ul><li>two conditions are equivalent </li></ul></ul><ul>...
Operator Precedence - Revisited <ul><li>Upper operator groups have precedence </li></ul>Operator Explanation Associativity...
Nested if statements <ul><li>if/else statements are inside other if/else statements </li></ul><ul><li>Method to select fro...
<ul><li>This may be written in C# as </li></ul><ul><ul><li>if  ( grade >=  90  )   Console.WriteLine(  &quot;A&quot;  ); e...
<ul><li>Most C# programmers prefer to use else if:  </li></ul><ul><li>if  ( grade >=  90  )   Console.WriteLine(  &quot;A&...
Short-circuit Evaluation <ul><li>Some subexpressions in Boolean expressions are not evaluated if the entire expression’s v...
Dangling Else Problem <ul><li>if ( x % 2  == 0)  </li></ul><ul><li>  if ( x < 0 )  </li></ul><ul><li>Console.WriteLine( &q...
Solution to Dangling Else Problem  <ul><ul><li>if ( x % 2  == 0)  </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>...
switch  statement <ul><li>The  switch multiple-selection  statement performs different actions based on the value of an ex...
<ul><li>private void IncrementLetterGradeCounter( int grade ) </li></ul><ul><li>{ </li></ul><ul><li>switch ( grade / 10 ) ...
Flow diagram of  switch
<ul><li>The expression after each  case  can be only a constant integral expression or a constant string expression. </li>...
From Selection to Repetition <ul><li>The if statement and if/else statement allow a  block  of statements to be executed s...
Flow diagram of while loop <ul><li>if (test)  while (test) </li></ul><ul><li>{  { </li></ul><ul><li>statement list ;  stat...
Sum Example: why we need loops? <ul><li>We want to find the sum of 10 positive values </li></ul><ul><li>We can write: </li...
Sum Example (not in book) <ul><li>What if we want to compute the sum of  </li></ul><ul><ul><li>100 values  </li></ul></ul>...
Another simple example <ul><li>Calculate the sum of the integer numbers between 1 and 10 </li></ul><ul><li>int sum = 0;  /...
Walkthrough of the example <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while (i <= 10) </li></ul><...
Walkthrough of the example <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while (i <= 10) </li></ul><...
Walkthrough of the example <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while (i <= 10) </li></ul><...
Walkthrough of the example <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while (i <= 10) </li></ul><...
while  loop syntax <ul><ul><li>< initialization >   </li></ul></ul><ul><ul><li>while (< test >)  </li></ul></ul><ul><ul><l...
while  loop sum example <ul><li>Sum of numbers from 1..10 </li></ul><ul><ul><li>int sum = 0; </li></ul></ul><ul><ul><li>in...
Counter-controlled  loop example <ul><li>Consider the following problem statement: </li></ul><ul><ul><li>A class of 10 stu...
Another  Counter-controlled  loop algorithm <ul><li>set total to zero </li></ul><ul><li>set grade counter to one </li></ul...
Counter-controlled  loop code ( Counting_While.sln ) <ul><li>// initializatio n </li></ul><ul><li>total = 0;  // initializ...
Sentinel-controlled  loop example <ul><li>Consider the following problem: </li></ul><ul><ul><li>Develop a class-averaging ...
Sentinel-controlled  algorithm <ul><li>initialize total to zero </li></ul><ul><li>initialize counter to zero </li></ul><ul...
Let’s see  Sentinel_While.sln <ul><li>// initialization phase </li></ul><ul><li>total = 0;  // initialize total </li></ul>...
for  loop syntax compared with  while <ul><li>< initialization >   </li></ul><ul><li>while (< test >)  </li></ul><ul><li>{...
Example <ul><li>Calculate the sum of the integer numbers between 1 and 10 </li></ul><ul><li>int sum = 0;  // this program ...
Same example with  for  loop <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while ( i <= 10 ) </li></...
Scope of the counter variable in  for <ul><ul><li>for ( int i=1 ;  i <= 10 ;  i=i+1 ) </li></ul></ul><ul><li>If the  initi...
for  loop syntax <ul><li>Comma-separated lists that enable you to use multiple initialization expressions or multiple incr...
Increment and Decrement Operators <ul><li>C# provides operators for adding or subtracting 1 from a numeric variable </li><...
Bad loops <ul><li>for (int i = 10;  i < 5 ; i=i+1)  </li></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>Console.WriteLine(&...
<ul><li>What is the problem with the code below? </li></ul><ul><ul><li>cannot say infinite loop for sure, depends on input...
Other Common Problems <ul><li>Easy to iterate one more or one less times </li></ul><ul><li>Test each loop with the inputs ...
Developing Loops <ul><li>Some loops are easy to develop, others are not </li></ul><ul><li>Sometimes the proper loop test a...
Factorial <ul><li>n! = 1 x 2 x … x n is “n factorial” ;  used  in math, statistics  </li></ul><ul><li>long factorial(long ...
Factorial <ul><ul><li>long Factorial(int num) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>long product = 1; </...
Downward-counting loop <ul><li>Calculate n to the power of m: n m =nxnx…xn </li></ul><ul><li>Example: 2 5 =2x2x2x2x2=32 </...
Exercise: Determining if a number is Prime <ul><li>1 is NOT prime, 2 is prime, 3 is prime, 5 is prime, 17 is prime, … 137,...
Nested loops – Example <ul><li>Write a function to display a perpendicular isosceles triangle of stars (perpendicular side...
Exercise: Multiplication Table <ul><li>On i th  line print, i*1, i*2, i*3, ... , i*i </li></ul><ul><ul><li>Total number of...
The  do-while  loop <ul><li>Similar to while loop, but the test is after the execution of the loop body </li></ul><ul><li>...
foreach <ul><li>Good with arrays or collections, we will revisit </li></ul>
<ul><li>The  break  statement causes immediate exit from a statement. </li></ul>When  count  is  5 , the  break  statement...
break  and  continue <ul><li>The  continue statement  skips the remaining statements in the loop body and tests whether to...
Skipping to the next iteration when  count  is  5 .  Console.Write  skips  5  because of the  continue  statement. continue
Upcoming SlideShare
Loading in …5
×

Control All

1,231 views

Published on

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

Control All

  1. 1. if-else, switch, while, for, do-while Control Statements
  2. 2. Conditional Statements <ul><li>So far statements of our programs execute sequentially one after another. </li></ul><ul><li>What happens when </li></ul><ul><ul><li>we want to execute a statement depending on a condition? </li></ul></ul><ul><ul><ul><li>e.g. If there is enough money in the bank account, give the money </li></ul></ul></ul><ul><ul><li>we want to execute one statement when a condition holds and another statement when a condition does not hold? </li></ul></ul><ul><ul><ul><li>e.g. If dollar is high, sell dollar. Otherwise, buy dollar. </li></ul></ul></ul><ul><ul><li>we want to select from many statements according to one or more criteria ( selection ). </li></ul></ul><ul><ul><ul><li>e .g. If dollar is high and euro is low, sell dollar and buy euro. If dollar is low and euro is high, sell euro and buy dollar. If both of them are high, sell both and buy YTL. </li></ul></ul></ul><ul><li>You achieve conditional execution with if-else statements </li></ul>
  3. 3. Syntax <ul><ul><li>if ( < condition > ) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li><s tatement_true_1> ; </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>< statement_true_N> ; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li><s tatement_false_1> ; </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>< statement_false_N> ; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>If condition is TRUE then </li></ul><ul><ul><li>s tatement_true_1 … </li></ul></ul><ul><ul><li>s tatement_true_N </li></ul></ul><ul><ul><li>are executed, </li></ul></ul><ul><li>if condition is FALSE </li></ul><ul><ul><li>statement_false_1 … </li></ul></ul><ul><ul><li>s tatement_false_N </li></ul></ul><ul><ul><li>are executed. </li></ul></ul><ul><ul><li>if ( < condition > ) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li><s tatement_true_1> ; </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>< statement_true_N> ; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>else and statement_false’s are optional </li></ul><ul><ul><li>if condition is FALSE then nothing will be executed and execution continues with the next statement in the program </li></ul></ul><ul><li><condition> must be in brackets </li></ul>
  4. 4. Another Syntax (without { }) <ul><ul><li>if (< condition >) </li></ul></ul><ul><ul><li><s tatement_true> ; </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li><s tatement_false> ; </li></ul></ul><ul><ul><li>if (< condition >) </li></ul></ul><ul><ul><li><s tatement_true> ; </li></ul></ul><ul><li>Can be used when there is only one statement </li></ul><ul><li>Not suggested (we will see why) </li></ul>
  5. 5. Flow diagram of if-else test condition true statements true next statement false false statements
  6. 6. if-else example <ul><li>Write a program that inputs two integer numbers and displays the maximum one. </li></ul><ul><li>Two solutions </li></ul><ul><ul><li>using if and else together (Maximum1.cs) </li></ul></ul><ul><ul><li>using only if (no else) (Maximum2.cs) </li></ul></ul>
  7. 7. Boolean type and expressions <ul><li>The condition in an if statement must be a Boolean expression (named for George Boole) </li></ul><ul><ul><li>Values are true or false </li></ul></ul><ul><ul><li>bool is a built-in value type like int, double </li></ul></ul><ul><ul><li>int degrees; </li></ul></ul><ul><li>bool isHot = false; </li></ul><ul><li>Console.WriteLine(&quot;enter temperature: “); </li></ul><ul><li>degrees = Convert.ToInt32(Console.ReadLine()); </li></ul><ul><li>if (degrees > 35) </li></ul><ul><li>{ </li></ul><ul><li> isHot = true; </li></ul><ul><li>} </li></ul>
  8. 8. <ul><li>The conditional operator ( ?: ) can be used in place of an if…else statement. </li></ul><ul><li>Console.WriteLine( grade >= 60 ? &quot;Passed&quot; : &quot;Failed&quot; ); </li></ul><ul><ul><ul><li>The first operand is a boolean expression that evaluates to true or false . </li></ul></ul></ul><ul><ul><ul><li>The second operand is the value if the expression is true </li></ul></ul></ul><ul><ul><ul><li>The third operand is the value if the expression is false. </li></ul></ul></ul>Conditional operator ( ?: )
  9. 9. Relational Operators <ul><li>Relational operators are used to compare values: </li></ul><ul><li>They take two operands </li></ul><ul><ul><li>operands can be literals, variables or expressions </li></ul></ul><ul><li>Used for many types </li></ul><ul><ul><li>numeric comparisons </li></ul></ul><ul><ul><li>string comparisons (alphabetical) </li></ul></ul>< less than number < 5 <= less than or equal number <= 0 > greater than num1 > num2 >= greater than or equal num1 >= num2 == equality check num1 == 0 != inequality check num1 != num2
  10. 10. Logical operators <ul><li>Boolean expressions can be combined using logical operators: AND, OR, NOT </li></ul><ul><ul><li>In C# we use && || ! respectively </li></ul></ul>A B A || B A && B true true true true true false true false false true true false false false false false A ! A true false false true
  11. 11. Example <ul><li>Range check: between 0 and 100 (includes 0 and 100), or not? </li></ul><ul><ul><li>If so, display a message saying that the number is in the range. </li></ul></ul><ul><ul><li>If not, the message should say “out of the range”. </li></ul></ul><ul><li>Solution 1: using logical AND operator </li></ul><ul><ul><li>if (num >= 0 && num <= 100) </li></ul></ul><ul><ul><li>Console.Write(&quot;number is in the range&quot;); </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li> Console.Write(&quot;number is out of range&quot;); </li></ul></ul><ul><li>Solution 2: using logical AND and NOT operators </li></ul><ul><ul><li>if ( ! (num >= 0 && num <= 100) ) </li></ul></ul><ul><ul><li> Console.Write(&quot;number is out of range&quot;); </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li> Console.Write(&quot;number is in the range&quot;); </li></ul></ul><ul><li>Solution 3: using logical OR operator </li></ul><ul><ul><li>if (num < 0 || num > 100) </li></ul></ul><ul><ul><li>Console.Write(&quot;number is out of range&quot;); </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li>Console.Write(&quot;number is in the range&quot;); </li></ul></ul>
  12. 12. De Morgan’s Rules <ul><li>Compare solution 2 and 3 </li></ul><ul><ul><li>two conditions are equivalent </li></ul></ul><ul><ul><ul><li>( ! (num >= 0 && num <= 100) ) </li></ul></ul></ul><ul><ul><ul><li>( num < 0 || num > 100 ) </li></ul></ul></ul><ul><li>De Morgan’s Rules (assume a and b are two boolean expressions) </li></ul><ul><ul><li>! (a && b) = !a || !b </li></ul></ul><ul><ul><li>! (a || b) = !a && !b </li></ul></ul><ul><li>De Morgan’a Rules can be generalized to several expressions (e.g. 4 boolean expressions case) </li></ul><ul><ul><li>! (a && b && c && d ) = !a || !b || !c || !d </li></ul></ul><ul><ul><li>! (a || b || c || d ) = !a && !b && !c && !d </li></ul></ul>
  13. 13. Operator Precedence - Revisited <ul><li>Upper operator groups have precedence </li></ul>Operator Explanation Associativity + - ! plus and minus signs, logical NOT right-to-left * / % multiplication, division and modulus left-to-right + - addition, subtraction left-to-right < <= > >= i nequality comparison operators left-to-right == != equal, not equal comparison left-to-right && logical and left-to-right || logical or left-to-right = += -= *= /= %= assignment operators right-to-left
  14. 14. Nested if statements <ul><li>if/else statements are inside other if/else statements </li></ul><ul><li>Method to select from multiple choices </li></ul><ul><li>Example: input a numeric grade and convert to letter grade </li></ul><ul><ul><li>90 .. 100 A </li></ul></ul><ul><ul><li>80 .. 89 B </li></ul></ul><ul><ul><li>70 .. 79 C </li></ul></ul><ul><ul><li>60 .. 69 D </li></ul></ul><ul><ul><li>0 .. 59 F </li></ul></ul><ul><ul><li>otherwise F </li></ul></ul>
  15. 15. <ul><li>This may be written in C# as </li></ul><ul><ul><li>if ( grade >= 90 ) Console.WriteLine( &quot;A&quot; ); else if ( grade >= 80 ) Console.WriteLine( &quot;B&quot; ); else if ( grade >= 70 ) Console.WriteLine( &quot;C&quot; ); else if ( grade >= 60 ) Console.WriteLine( &quot;D&quot; ); else Console.WriteLine( &quot;F&quot; ); </li></ul></ul>Nested if statements
  16. 16. <ul><li>Most C# programmers prefer to use else if: </li></ul><ul><li>if ( grade >= 90 ) Console.WriteLine( &quot;A&quot; ); else if ( grade >= 80 ) Console.WriteLine( &quot;B&quot; ); else if ( grade >= 70 ) Console.WriteLine( &quot;C&quot; ); else if ( grade >= 60 ) Console.WriteLine( &quot;D&quot; ); else Console.WriteLine( &quot;F&quot; ); </li></ul>Nested if statements (Cont.)
  17. 17. Short-circuit Evaluation <ul><li>Some subexpressions in Boolean expressions are not evaluated if the entire expression’s value is already known using the subexpression evaluated so far. </li></ul><ul><li>Rule : Evaluate the first (leftmost) boolean subexpression. If its value is enough to judge about the value of the entire expression, then stop there. Otherwise continue evaluation towards right. </li></ul><ul><ul><li>if (count != 0 && scores/count < 60) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> Console.WriteLine(&quot;low average&quot;); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>In this example, if the value of count is zero, then first subexpression becomes false and the second one is not evaluated. </li></ul></ul><ul><ul><li>In this way, we avoid “division by zero” error (that would cause to stop the execution of the program) </li></ul></ul><ul><ul><li>Alternative method to avoid division by zero without using short-circuit evaluation: </li></ul></ul><ul><ul><li>if (count != 0) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> if (scores/count < 60) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> Console.WriteLine(&quot;low average&quot;); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>} </li></ul></ul>
  18. 18. Dangling Else Problem <ul><li>if ( x % 2 == 0) </li></ul><ul><li> if ( x < 0 ) </li></ul><ul><li>Console.WriteLine( &quot; {0} is an even, negative number “ , x); </li></ul><ul><li>else </li></ul><ul><li> Console.WriteLine( &quot; {0} is an odd number “ , x); </li></ul><ul><li>What does it display for x=4? </li></ul><ul><li>The problem is that it displays “odd number” message for positive even numbers and zero. </li></ul><ul><li>Reason is that, although indentation says the reverse, else belongs to second (inner) if </li></ul><ul><ul><li>else belongs to the most recent if </li></ul></ul><ul><li>Solution: use braces (see next slide) </li></ul>
  19. 19. Solution to Dangling Else Problem <ul><ul><li>if ( x % 2 == 0) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> if ( x < 0 ) </li></ul></ul><ul><ul><li> Console.WriteLine( &quot; {0} is an even, negative number “ , x); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> Console.WriteLine( &quot; {0} is an odd number “ , x); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>Now else belongs to the first if </li></ul><ul><li>if – else matching rule </li></ul><ul><ul><li>Each else belongs to the nearest if for which there is no else and in the same compound block </li></ul></ul>
  20. 20. switch statement <ul><li>The switch multiple-selection statement performs different actions based on the value of an expression. </li></ul><ul><li>Each action is associated with the value of a constant integral expression or a constant string expression that the expression may assume. </li></ul><ul><li>Let’s see an example: GradeBookswitch.cs </li></ul>
  21. 21. <ul><li>private void IncrementLetterGradeCounter( int grade ) </li></ul><ul><li>{ </li></ul><ul><li>switch ( grade / 10 ) </li></ul><ul><li>{ </li></ul><ul><li>case 9: // grade was in the 90s </li></ul><ul><li>case 10: // grade was 100 </li></ul><ul><li>++aCount; </li></ul><ul><li>break; // necessary to exit switch </li></ul><ul><li>case 8: // grade was between 80 and 89 </li></ul><ul><li>++bCount; </li></ul><ul><li>break; // exit switch </li></ul><ul><li>case 7: // grade was between 70 and 79 </li></ul><ul><li>++cCount; </li></ul><ul><li>break; // exit switch </li></ul><ul><li>case 6: // grade was between 60 and 69 </li></ul><ul><li>++dCount; </li></ul><ul><li>break; // exit switch </li></ul><ul><li>default: // grade was less than 60 </li></ul><ul><li>++fCount; </li></ul><ul><li>break; // exit switch </li></ul><ul><li>} </li></ul><ul><li>} // end method IncrementLetterGradeCounter </li></ul>
  22. 22. Flow diagram of switch
  23. 23. <ul><li>The expression after each case can be only a constant integral expression or a constant string expression. </li></ul><ul><li>You can also use null and character constants which represent the integer values of characters. </li></ul><ul><li>The expression also can be a constant that contains a value which does not change for the entire application. </li></ul>switch statement
  24. 24. From Selection to Repetition <ul><li>The if statement and if/else statement allow a block of statements to be executed selectively: based on a condition </li></ul><ul><ul><li>Console.WriteLine(&quot;Please enter a non-negative number&quot;); </li></ul></ul><ul><ul><li>inputnumber = Convert.ToInt32(Console.ReadLine()); </li></ul></ul><ul><ul><li>if (inputnumber < 0) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>Console.WriteLine(inputnumber + &quot; is negative. Wrong Input&quot;); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>This piece of code does not ask another input number if the number is negative. </li></ul><ul><li>The while statement repeatedly executes a block of statements while the condition is true </li></ul><ul><ul><li>Console.WriteLine(&quot;Please enter a non-negative number&quot;); </li></ul></ul><ul><ul><li>inputnumber = Convert.ToInt32(Console.ReadLine()); </li></ul></ul><ul><ul><li>while (inputnumber < 0) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>Console.WriteLine(inputnumber + &quot; is negative! Try again&quot;); </li></ul></ul><ul><ul><li> inputnumber = Convert.ToInt32(Console.ReadLine()); </li></ul></ul><ul><ul><li>} </li></ul></ul>
  25. 25. Flow diagram of while loop <ul><li>if (test) while (test) </li></ul><ul><li>{ { </li></ul><ul><li>statement list ; statement list ; </li></ul><ul><li>} } </li></ul>test Statement list Next statement true false test Statement list Next statement true false
  26. 26. Sum Example: why we need loops? <ul><li>We want to find the sum of 10 positive values </li></ul><ul><li>We can write: </li></ul><ul><ul><li>int num1, num2, num3, num4, num5; </li></ul></ul><ul><ul><li>int sum; </li></ul></ul><ul><ul><li>cin >> num1 >> num2 >> num3 >> num4 >> num5; </li></ul></ul><ul><ul><li>sum = num1 + num2 + num3 + num4 + num5; </li></ul></ul><ul><ul><li>cin >> num1 >> num2 >> num3 >> num4 >> num5; </li></ul></ul><ul><ul><li>sum += num1 + num2 + num3 + num4 + num5; </li></ul></ul>
  27. 27. Sum Example (not in book) <ul><li>What if we want to compute the sum of </li></ul><ul><ul><li>100 values </li></ul></ul><ul><ul><li>an undetermined number of values </li></ul></ul><ul><li>What we need is a program to be able to read as many values as we want and then compute the sum </li></ul><ul><li>This is possible with loops </li></ul><ul><li>Good solution is to use loops. </li></ul><ul><ul><li>Code is developed on board. See sum10nums.cs </li></ul></ul><ul><li>This type of loops are called counting loops </li></ul><ul><ul><li>number of iterations is known </li></ul></ul>
  28. 28. Another simple example <ul><li>Calculate the sum of the integer numbers between 1 and 10 </li></ul><ul><li>int sum = 0; // this program piece </li></ul><ul><li>int i = 1; // calculates the sum of </li></ul><ul><li>while (i <= 10) // integers between and </li></ul><ul><li>{ // including 1 and 10 </li></ul><ul><li>sum = sum + i; </li></ul><ul><li>i += 1; </li></ul><ul><li>} </li></ul>
  29. 29. Walkthrough of the example <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while (i <= 10) </li></ul><ul><li>{ </li></ul><ul><li> sum = sum + i; </li></ul><ul><li> i = i + 1; </li></ul><ul><li>} </li></ul><ul><li>Console.Write(sum); </li></ul>i<=10 sum=sum+i; i=i+1; true Console.Write(sum); false 1 i sum 0 2 1
  30. 30. Walkthrough of the example <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while (i <= 10) </li></ul><ul><li>{ </li></ul><ul><li> sum = sum + i; </li></ul><ul><li> i = i + 1; </li></ul><ul><li>} </li></ul><ul><li>Console.Write(sum); </li></ul>i<=10 sum=sum+i; i=i+1; true false 2 i sum 1 3 3 Console.Write(sum);
  31. 31. Walkthrough of the example <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while (i <= 10) </li></ul><ul><li>{ </li></ul><ul><li> sum = sum + i; </li></ul><ul><li> i = i + 1; </li></ul><ul><li>} </li></ul><ul><li>Console.Write(sum); </li></ul>i<=10 sum=sum+i; i=i+1; true cout<<sum; false 3 i sum 3 4 6 Console.Write(sum);
  32. 32. Walkthrough of the example <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while (i <= 10) </li></ul><ul><li>{ </li></ul><ul><li> sum = sum + i; </li></ul><ul><li> i = i + 1; </li></ul><ul><li>} </li></ul><ul><li>Console.Write(sum); </li></ul>i<=10 sum=sum+i; i=i+1; true cout<<sum; false 10 i sum 45 11 55 Console.Write(sum);
  33. 33. while loop syntax <ul><ul><li>< initialization > </li></ul></ul><ul><ul><li>while (< test >) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li><s tatement1> ; </li></ul></ul><ul><ul><li>... </li></ul></ul><ul><ul><li>< statementN> ; </li></ul></ul><ul><ul><li>< update > </li></ul></ul><ul><ul><li>} </li></ul></ul>
  34. 34. while loop sum example <ul><li>Sum of numbers from 1..10 </li></ul><ul><ul><li>int sum = 0; </li></ul></ul><ul><ul><li>int i = 1; </li></ul></ul><ul><ul><li>while (i <= 10) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>sum = sum + i; </li></ul></ul><ul><ul><li>i = i + 1; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>Console.Write(sum); </li></ul></ul>initialization body statements update test
  35. 35. Counter-controlled loop example <ul><li>Consider the following problem statement: </li></ul><ul><ul><li>A class of 10 students took a quiz. The grades (integers in </li></ul></ul><ul><ul><li>the range 0 to 100) for this quiz are available to you. </li></ul></ul><ul><ul><li>Determine the class average on the quiz. </li></ul></ul><ul><li>The algorithm must input each grade, keep track of the total of all grades input, perform the averaging calculation and display the result. </li></ul>
  36. 36. Another Counter-controlled loop algorithm <ul><li>set total to zero </li></ul><ul><li>set grade counter to one </li></ul><ul><li>while grade counter is less than or equal to 10 </li></ul><ul><li> prompt the user to enter the next grade </li></ul><ul><li> input the next grade </li></ul><ul><li> add the grade into the total </li></ul><ul><li> add one to the grade counter </li></ul><ul><li>set the class average to the total divided by 10 </li></ul><ul><li>display the class average </li></ul>
  37. 37. Counter-controlled loop code ( Counting_While.sln ) <ul><li>// initializatio n </li></ul><ul><li>total = 0; // initialize the total </li></ul><ul><li>gradeCounter = 1; // initialize the loop counter </li></ul><ul><li>while ( gradeCounter <= 10 ) // test </li></ul><ul><li>{ </li></ul><ul><li>Console.Write( &quot;Enter grade: &quot; ); // prompt the user </li></ul><ul><li>grade = Convert.ToInt32( Console.ReadLine() ); // read grade </li></ul><ul><li>total = total + grade; // add the grade to total </li></ul><ul><li>gradeCounter = gradeCounter + 1; // update </li></ul><ul><li>} </li></ul><ul><li>// termination phase </li></ul><ul><li>average = total / 10; // integer division yields integer result </li></ul>
  38. 38. Sentinel-controlled loop example <ul><li>Consider the following problem: </li></ul><ul><ul><li>Develop a class-averaging application that processes grades for an arbitrary number of students each time it is run. </li></ul></ul><ul><li>In this example, no indication is given of how many grades the user will enter during the application’s execution. </li></ul>
  39. 39. Sentinel-controlled algorithm <ul><li>initialize total to zero </li></ul><ul><li>initialize counter to zero </li></ul><ul><li>prompt the user to enter the first grade </li></ul><ul><li>input the first grade (possibly the sentinel) </li></ul><ul><li>while the user has not yet entered the sentinel </li></ul><ul><li> add this grade into the running total </li></ul><ul><li> add one to the grade counter </li></ul><ul><li> prompt the user to enter the next grade </li></ul><ul><li> input the next grade (possibly the sentinel) </li></ul><ul><li>if the counter is not equal to zero </li></ul><ul><li> set the average to the total divided by the counter </li></ul><ul><li> display the average </li></ul><ul><li>else </li></ul><ul><li> display “No grades were entered” </li></ul>
  40. 40. Let’s see Sentinel_While.sln <ul><li>// initialization phase </li></ul><ul><li>total = 0; // initialize total </li></ul><ul><li>gradeCounter = 0; // initialize loop counter </li></ul><ul><li>// prompt for and read a grade from the user </li></ul><ul><li>Console.Write(&quot;Enter grade or -1 to quit: &quot;); </li></ul><ul><li>grade = Convert.ToInt32(Console.ReadLine()); </li></ul><ul><li>// loop until sentinel value is read from the user </li></ul><ul><li>while ( grade != -1 ) </li></ul><ul><li>{ </li></ul><ul><li> total = total + grade; // add grade to total </li></ul><ul><li> gradeCounter = gradeCounter + 1; // increment counter </li></ul><ul><li> // prompt for and read the next grade from the user </li></ul><ul><li> Console.Write(&quot;Enter grade or -1 to quit: &quot;); </li></ul><ul><li>grade = Convert.ToInt32(Console.ReadLine()); </li></ul><ul><li>} </li></ul>
  41. 41. for loop syntax compared with while <ul><li>< initialization > </li></ul><ul><li>while (< test >) </li></ul><ul><li>{ </li></ul><ul><li><s tatement1> ; </li></ul><ul><li>... </li></ul><ul><li>< statementN> ; </li></ul><ul><li>< update > </li></ul><ul><li>} </li></ul><ul><li>for (< initialization > ; </li></ul><ul><li> < test >; </li></ul><ul><li> < update > ) </li></ul><ul><li>{ </li></ul><ul><li><s tatement1> ; ...    < statementN> ; </li></ul><ul><li>} </li></ul>
  42. 42. Example <ul><li>Calculate the sum of the integer numbers between 1 and 10 </li></ul><ul><li>int sum = 0; // this program piece </li></ul><ul><li>int i = 1; // calculates the sum of </li></ul><ul><li>while (i <= 10) // integers between and </li></ul><ul><li>{ // including 1 and 10 </li></ul><ul><li>sum = sum + i; </li></ul><ul><li>i = i + 1; </li></ul><ul><li>} </li></ul>
  43. 43. Same example with for loop <ul><li>int sum = 0; </li></ul><ul><li>int i = 1; </li></ul><ul><li>while ( i <= 10 ) </li></ul><ul><li>{ </li></ul><ul><li> sum = sum + i; </li></ul><ul><li> i = i + 1; </li></ul><ul><li>} </li></ul><ul><li>int sum = 0; </li></ul><ul><li>for ( int i=1 ; i <= 10 ; i=i+1 ) </li></ul><ul><li>{ </li></ul><ul><li> sum = sum + i; </li></ul><ul><li>} </li></ul>
  44. 44. Scope of the counter variable in for <ul><ul><li>for ( int i=1 ; i <= 10 ; i=i+1 ) </li></ul></ul><ul><li>If the initialization expression declares the control variable, the control variable will not exist outside the for statement. </li></ul><ul><li>This restriction is known as the variable’s scope . </li></ul><ul><li>Similarly, a local variable can be used only in the method that declares the variable and only from the point of declaration. </li></ul><ul><ul><li>int i; </li></ul></ul><ul><ul><ul><li>for ( i=1 ; i <= 10 ; i=i+1 ) </li></ul></ul></ul>
  45. 45. for loop syntax <ul><li>Comma-separated lists that enable you to use multiple initialization expressions or multiple increment expressions: </li></ul><ul><li>for ( int i = 2 ; i <= 20 ; total += i , i += 2 ) ; // empty statement </li></ul>
  46. 46. Increment and Decrement Operators <ul><li>C# provides operators for adding or subtracting 1 from a numeric variable </li></ul><ul><ul><li>The unary increment operator , ++ </li></ul></ul><ul><ul><li>The unary decrement operator , -- . </li></ul></ul>
  47. 47. Bad loops <ul><li>for (int i = 10; i < 5 ; i=i+1) </li></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>Console.WriteLine(&quot;How many times do I print?&quot;); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>for (int i = 10; i >= 1 ; i=i+1) </li></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> Console.WriteLine(&quot;How many times do I print?&quot;); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>int i = 1; </li></ul><ul><ul><li>while (i < 20) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> Console.WriteLine(&quot;How many times do I print?&quot;); </li></ul></ul><ul><ul><li>} </li></ul></ul>
  48. 48. <ul><li>What is the problem with the code below? </li></ul><ul><ul><li>cannot say infinite loop for sure, depends on input number </li></ul></ul><ul><ul><ul><li>f or example, if num is an odd number, then the loop is infinite </li></ul></ul></ul><ul><li> </li></ul><ul><ul><li> int num = Convert.ToInt32(Console.ReadLine()); </li></ul></ul><ul><ul><li>int start = 0; </li></ul></ul><ul><ul><li>while (start != num) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li> start += 2; </li></ul></ul><ul><ul><li> Console.WriteLine( start); </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>How to fix? </li></ul><ul><ul><li>You can check whether num is even before starting the loop. </li></ul></ul><ul><ul><ul><li>if (num % 2 == 0) </li></ul></ul></ul><ul><ul><ul><li>{ while (start != num) </li></ul></ul></ul><ul><ul><ul><li>{ start += 2; </li></ul></ul></ul><ul><ul><ul><li> Console.WriteLine(start); </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>Infinite loops
  49. 49. Other Common Problems <ul><li>Easy to iterate one more or one less times </li></ul><ul><li>Test each loop with the inputs that cause: </li></ul><ul><ul><li>zero iterations of the loop body </li></ul></ul><ul><ul><li>one iteration of the loop body </li></ul></ul><ul><ul><li>maximum number of iterations </li></ul></ul><ul><ul><li>one less than the maximum number of iterations </li></ul></ul><ul><li>Use the debugger and watch the variables. </li></ul>
  50. 50. Developing Loops <ul><li>Some loops are easy to develop, others are not </li></ul><ul><li>Sometimes the proper loop test and body are hard to design </li></ul><ul><li>Practice helps, but remember : </li></ul><ul><ul><li>Good design comes from experience, experience comes from bad design </li></ul></ul>
  51. 51. Factorial <ul><li>n! = 1 x 2 x … x n is “n factorial” ; used in math, statistics </li></ul><ul><li>long factorial(long n) </li></ul><ul><li>// pre: 0 <= n </li></ul><ul><li>// post: returns n! (1 x 2 x … x n) </li></ul><ul><li>Similar to sum, but this time we will calculate a product within the loop. At the end we will return the final product. </li></ul><ul><ul><li>The loop will iterate n times, multiplying by 1, 2, …, n </li></ul></ul><ul><ul><li>Suppose we use a variable called product to hold the result , then product is n! when the loop terminates. Then we will return it at the end. </li></ul></ul>
  52. 52. Factorial <ul><ul><li>long Factorial(int num) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>long product = 1; </li></ul></ul><ul><ul><li>int count = 0; </li></ul></ul><ul><ul><li>while (count < num) </li></ul></ul><ul><ul><li>{ </li></ul></ul><ul><ul><li>count += 1; </li></ul></ul><ul><ul><li>product *= count; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><ul><li>return product; </li></ul></ul><ul><ul><li>} </li></ul></ul><ul><li>Issues </li></ul><ul><ul><li>Why did we use long? What happens if we use int instead? </li></ul></ul><ul><ul><li>What happens if we initialize count to 1? </li></ul></ul><ul><li>See factorial.cpp </li></ul>
  53. 53. Downward-counting loop <ul><li>Calculate n to the power of m: n m =nxnx…xn </li></ul><ul><li>Example: 2 5 =2x2x2x2x2=32 </li></ul><ul><ul><ul><li>int power = 1; </li></ul></ul></ul><ul><ul><ul><li>int n, m; </li></ul></ul></ul><ul><ul><ul><li>for (int i = m; i <= 1; i-- ) </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li> power = power * n; </li></ul></ul></ul><ul><ul><ul><li>} </li></ul></ul></ul>
  54. 54. Exercise: Determining if a number is Prime <ul><li>1 is NOT prime, 2 is prime, 3 is prime, 5 is prime, 17 is prime, … 137, 193? </li></ul><ul><ul><li>W e do not need to check even numbers other than 2 (2 is a special case) </li></ul></ul><ul><ul><li>To check 193 , divide it by 3, 5, 7, 9, 11, 13 </li></ul></ul><ul><ul><ul><li>Note that 14x14 = 196, so 13 largest potential factor? </li></ul></ul></ul><ul><ul><ul><li>We can use modulus operator to check divisibility </li></ul></ul></ul><ul><li>Check odd numbers as potential divisors </li></ul><ul><ul><li>Watch out for 2, it is a special case </li></ul></ul><ul><ul><li>How far should we go to check potential divisors? </li></ul></ul><ul><ul><ul><li>up to and including Math.Sqrt(number) + 1 </li></ul></ul></ul><ul><ul><ul><li>If there was a bigger factor, a smaller factor would exist. And this smaller one must have been checked before. So we do not need to go beyond this limit. </li></ul></ul></ul><ul><ul><ul><li>+1 is there to make sure that there will be no problems with precision </li></ul></ul></ul><ul><ul><li>Write code as exercise at home </li></ul></ul>
  55. 55. Nested loops – Example <ul><li>Write a function to display a perpendicular isosceles triangle of stars (perpendicular side length is parameter) </li></ul><ul><ul><li>e.g. if side length is 6 , the output should look like </li></ul></ul><ul><ul><ul><li>* </li></ul></ul></ul><ul><ul><ul><li>** </li></ul></ul></ul><ul><ul><ul><li>*** </li></ul></ul></ul><ul><ul><ul><li>**** </li></ul></ul></ul><ul><ul><ul><li>***** </li></ul></ul></ul><ul><ul><ul><li>****** </li></ul></ul></ul><ul><ul><li>See drawtriangle .cs </li></ul></ul><ul><ul><li>Exercise: write the same loops downward-counting this time. </li></ul></ul>
  56. 56. Exercise: Multiplication Table <ul><li>On i th line print, i*1, i*2, i*3, ... , i*i </li></ul><ul><ul><li>Total number of lines is an input. Display lines starting with 1. </li></ul></ul><ul><li>Please enter the number of lines in the multiplication table: 9 </li></ul><ul><li>1 </li></ul><ul><li>2 4 </li></ul><ul><li>3 6 9 </li></ul><ul><li>4 8 12 16 </li></ul><ul><li>5 10 15 20 25 </li></ul><ul><li>6 12 18 24 30 36 </li></ul><ul><li>7 14 21 28 35 42 49 </li></ul><ul><li>8 16 24 32 40 48 56 64 </li></ul><ul><li>9 18 27 36 45 54 63 72 81 </li></ul>
  57. 57. The do-while loop <ul><li>Similar to while loop, but the test is after the execution of the loop body </li></ul><ul><li>The while loop may never execute, do-while loop executes at least once </li></ul><ul><ul><ul><li>< initialization > </li></ul></ul></ul><ul><ul><ul><li>do </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li> <s tatement1> ;    ...   < statementN> ; </li></ul></ul></ul><ul><ul><ul><li> < update > </li></ul></ul></ul><ul><ul><ul><li>} while (< condition >); </li></ul></ul></ul><ul><li>Example: Prompt for a number between 0 and 100, loop until such a number is entered ( user should enter at least one number) </li></ul><ul><ul><ul><li>do </li></ul></ul></ul><ul><ul><ul><li>{ </li></ul></ul></ul><ul><ul><ul><li> Console.WriteLine(&quot;enter number in range [0..100]&quot;); </li></ul></ul></ul><ul><ul><ul><li> num = Convert.ToInt32(Console.ReadLine()); </li></ul></ul></ul><ul><ul><ul><li>} while (num < 0 || num > 100 ); </li></ul></ul></ul>Don’t forget
  58. 58. foreach <ul><li>Good with arrays or collections, we will revisit </li></ul>
  59. 59. <ul><li>The break statement causes immediate exit from a statement. </li></ul>When count is 5 , the break statement terminates the for statement. break
  60. 60. break and continue <ul><li>The continue statement skips the remaining statements in the loop body and tests whether to proceed with the next iteration of the loop. </li></ul><ul><li>In a for statement, the increment expression executes, then the application evaluates the loop-continuation test. </li></ul>Software Engineering Some programmers feel that break and continue statements violate structured programming, since the same effects are achievable with structured programming techniques.
  61. 61. Skipping to the next iteration when count is 5 . Console.Write skips 5 because of the continue statement. continue

×