27 Interactive for Loops contd Program 511 for statement creates a loop Loop

27 interactive for loops contd program 511 for

This preview shows page 27 - 38 out of 41 pages.

27
Image of page 27
Interactive for Loops (cont'd.) Program 5.11: for statement creates a loop – Loop executed five times Actions performed in each loop – User prompted to enter a number – Number added to the total A First Book of C++ 4th Edition 28
Image of page 28
Interactive for Loops (cont'd.) Initialization variations: – Alternative 1: initialize total outside the loop and count inside the loop as in Program 5.11 – Alternative 2: initialize both total and count inside loop for (total = 0.0, count = 0; count < MAXCOUNT; count++) – Alternative 3: initialize and declare both total and count inside loop for (double total = 0.0, int count = 0; count < MAXCOUNT; count++) A First Book of C++ 4th Edition 29
Image of page 29
Nested Loops A loop contained within another loop • Example: for(i = 1; i <= 5; i++) // start of outer loop { cout << "\ni is now " << i << endl; for(j = 1; j <= 4; j++) // start of inner loop { cout << " j = " << j; } // end of inner loop } // end of outer loop A First Book of C++ 4th Edition 30
Image of page 30
Nested Loops (cont'd.) Outer (first) loop: – Controlled by value of i Inner (second) loop: – Controlled by value of j • Rules: – For each single trip through outer loop, inner loop runs through its entire sequence – Different variable to control each loop – Inner loop statements contained within outer loop A First Book of C++ 4th Edition 31
Image of page 31
Nested Loops (cont'd.) A First Book of C++ 4th Edition 32
Image of page 32
The do-while Statement A repetition statement that evaluates an expression at the end of the statement – Allows some statements to be executed before an expression is evaluated –for and while evaluate an expression at the beginning of the statement • Format: do statement; while (expression);// don’t forget final ; A First Book of C++ 4th Edition 33
Image of page 33
A First Book of C++ 4th Edition 34
Image of page 34
Validity Checks Provided by do-while statement through filtering of user-entered input • Example: do { cout << "\nEnter an identification number: "; cin >> idNum; if (idNum < 100 || idNum > 1999) { cout << "\n An invalid number was just entered" << "\nPlease check the ID number and reenter"; } else break; // break if a valid ID number was entered } while(1) ; // this expression is always true A First Book of C++ 4th Edition 35
Image of page 35
Common Programming Errors “Off by one” errors: loop executes one time too many or one time too few – Initial and final conditions to control loop must be carefully constructed Inadvertent use of assignment operator, = , in place of the equality operator, == – This error is not detected by the compiler A First Book of C++ 4th Edition 36
Image of page 36