CS149D Elements of Computer Science Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture 20: 11/7/2002 Lecture 20: 11/7/2002 CS149D Fall 2002
Outline Looping do-while loop for loop Break and continue statements within loops Nested Loops Lecture 20: 11/7/2002 CS149D Fall 2002
The do-while Loop1/2 Condition True ? Execute while Statement(s) Continue to next statement No Yes do statement; while (condition); { statement(s); }while (condition); Lecture 20: 11/7/2002 CS149D Fall 2002
The do-while Loop2/2 Print 0, 4,16,36,64,100 (0, 22,42,62,82,102) // while loop solution int x = 0; while (x <= 10) { cout << x*x <<endl; x +=2; } //do-while loop solution int x = 0; do { cout << x*x <<endl; x +=2; } while (x <= 10); Lecture 20: 11/7/2002 CS149D Fall 2002
The for Loop1/2 Execute init statement for (x = 0; x <=10 ; x+=2) Exit Condition Execute for_statement(s) Execute x +=2 Execute next statement True False for (x = 0; x <=10 ; x+=2) cout << x*x <<endl; x = 0 init statement x <=10 Exit condition x +=2 executed before starting a new iteration Lecture 20: 11/7/2002 CS149D Fall 2002
The for Loop2/2 Print 0, 4,16,36,64,100 (0, 22,42,62,82,102) // while loop solution int x = 0; while (x <= 10) { cout << x*x <<endl; x +=2; } //do-while loop solution int x = 0; do { cout << x*x <<endl; x +=2; } while (x <= 10); // for loop solution int x; for (x = 0; x <=10 ; x+=2) cout << x*x <<endl; Lecture 20: 11/7/2002 CS149D Fall 2002
Variations of the for Loop Init statement, Exit Condition, and expression 2 can all be null //infinite Loop for ( ; ; ) cout << “Hi”; //Equivalent to while (true) for ( ; inputVal != -1; ) cin >> inputVal; //Equivalent to while (inputVal != -1) Lecture 20: 11/7/2002 CS149D Fall 2002
The break and continue statements1/2 The break statement Exit immediately from its enclosing loop The continue statement Skip any remaining statements in the current iteration, and start a new iteration of the enclosing loop In while or do-while loop, the condition is evaluated to determine whether or not to start a new iteration In a for loop, the second expression is executed, then condition is evaluated Lecture 20: 11/7/2002 CS149D Fall 2002
The break and continue statements2/2 // break example sum = 0; for (int k=1;k<21;k++) { cin >>x; if (x > 10) break; sum += x; } cout << sum; // continue example sum = 0; for (int k=1;k<21;k++) { cin >>x; if (x > 10) continue; sum += x; } cout << sum; Lecture 20: 11/7/2002 CS149D Fall 2002
Nested Loops for (i = 1; i <=5; i ++) { for (j = 1; j <=i; j++) Print the following triangle 1 12 123 1234 12345 for (i = 1; i <=5; i ++) { for (j = 1; j <=i; j++) cout << j; cout <<endl; } Lecture 20: 11/7/2002 CS149D Fall 2002