CS101 Computer Programming I Chapter 4 Extra Examples
while Loop Example Write a while loop to print all the even integers between 0 and 20. int i = 0; while ( i <= 20 ) { if ( i % 2 = 0 ) System.out.printf( "%d ", i ); i++; } 2
Slide 3- 3 for/while Loop Comparison Write a code to add the numbers from 1 to 10. Using a while loop: sum = 0; n = 1; while(n <= 10) // add the numbers { sum = sum + n; n=n+1; //n++; } Using a for loop: sum = 0; for (n = 1; n <= 10; n++) //add the numbers sum = sum + n;
Slide 3- 4 while loop: Exit on Flag Caution Consider this loop to identify a student with a grade of 90 or better to find a tutor for week students. (We assume the method compute_grade() has already been defined) (In this example the variable grade serves as the flag) int n = 1; grade = compute_grade(n); while (grade < 90) { n=n+1; //n++; grade = compute_grade(n); } System.out.printf( “Student number %d may be a tutor.\nThis student has a score of %f", n, grade );
Slide 3- 5 The Problem The loop on the previous slide might not stop at the end of the list of students if no student has a grade of 90 or higher It is a good idea to use a second flag to ensure that there are still students to consider The code on the following slide shows a better solution
Slide 3- 6 The Exit On Flag Solution This code solves the problem of having no student grade at 90 or higher : int n=1; grade = compute_grade(n); while (( grade = 90) System.out.printf( “Student number %d may be a tutor.\nThis student has a score of %f", n, grade ); else cout << "No student has a high score.";
Slide 3- 7 List Ended With a Sentinel Value nonnegative integers nonnegative integersA while loop is typically used to end a loop using the list ended with a sentinel value method. cout > number; while (number > =0) { sum = sum + number; cout > number; } Notice that the sentinel value is read, but not processed i.e. -1 is read but not added to sum
Slide 3- 8 Debugging Loops Common errors involving loops include Off-by-one errors in which the loop executes one too many or one too few times Infinite loops usually result from a mistake in the Boolean expression that controls the loop
Slide 3- 9 Fixing Off By One Errors Check your comparison: should it be < or <=? Check that the initialization uses the correct value Does the loop handle the zero iterations case? ( in case, if the loop may sometimes be iterated zero times)
Slide Fixing Infinite Loops Check the direction of inequalities: ? Test for rather than equality (= =) Remember that doubles are really only approximations
Slide More Loop Debugging Tips Be sure that the mistake is really in the loop Trace the variable to observe how the variable changes Tracing a variable is watching its value change during execution Many systems include utilities to help with this cout statements can be used to trace a value
Slide Debugging Example containing the product of the numbers through 5 The following code is supposed to conclude with the variable product containing the product of the numbers 2 through 5 int next = 2, product = 1; while (next < 5) { next = next+1; //next++ product = product * next; }
Slide 13 Tracing Variables Add temporary print statements to trace variables int next = 2, product = 1; while (next < 5) { next = next+1; //next++ product = product * next; System.out.printf( “next= %d product= %d.\n", next, product ); } next = 3 product = 3 next = 4 product = 12 next = 5 product = 60 Press any key to continue... Required was from 2 to 5 not from 3
Slide First Fix The cout statements added to the loop show us that the loop never multiplied by 2 Solve the problem by moving the statement next++ int next = 2, product = 1; while (next < 5) { product = product * next; System.out.printf( “next= %d product= %d.\n", next, product ); next = next+1; //next++ } There is still a problem! next = 2 product = 2 next = 3 product = 6 next = 4 product = 24 Press any key to continue...
Slide Second Fix Re-testing the loop shows us that now the loop never mulitplies by 5 The fix is to use <= instead of < in our comparison int next = 2, product = 1; while (next <= 5) { product = product * next; System.out.printf( “next= %d product=%d.\n", next, product ); next = next+1; //next++ } next = 2 product = 2 next = 3 product = 6 next = 4 product = 24 next = 5 product = 120 Press any key to continue...
Slide Loop Testing Guidelines Every time a program is changed, it must be retested. Changing one part may require a change to another. Every loop should at least be tested using input to cause: Zero iterations of the loop body One iteration of the loop body One less than the maximum number of iterations The maximum number of iterations
Slide Infinite Loops Loops that never stop are infinite loops. The loop body should contain a line that will eventually cause the Boolean expression to become false. If you make a mistake and write your program so that the Boolean expression is always true, then the loop will run forever. A loop that runs forever is called an infinite loop.
Slide Infinite Loops (Cont.) Example: Print the positive even numbers less than 12. x = 2; while (x != 12) { System.out.println( x ); x = x + 2; } Print the positive odd numbers less than 12. x = 1; while (x != 12) { System.out.println( x ); x = x + 2; } This will create an infinite loop since the value of x goes from 11 to 13 and it’s never equal to 12. Better to use this comparison: while ( x < 12)
Slide Example Show the output of this code if x is of type int? int x = 10; while ( x > 0) { System.out.println( x ); x = x - 3; } Show the output of the previous code using the comparison x 0? int x = 10; while ( x < 0) { System.out.println( x ); x = x - 3; }