lec05-flow_control_2

# lec05-flow_control_2 - CSC 1111 Introduction to Computing...

This preview shows pages 1–9. Sign up to view the full content.

1 CSC 1111 Introduction to Computing using C++ for loop and nested loop, break and continue

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
2 Outline for loops Nested loops break statement continue statement
3 Review: Counting using while loops What are the three "must-have" in using a while loop to execute " statement " 10 times? i = 0 ; // Initialization while ( i < 10 ) { // Stopping condition statement ; i++; // Increase (or decrease) // loop variable }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
4 Counting using for loops for ( i = 0 ; i < 10 ; i++ ) { statement ; } i = 0 ; while ( i < 10 ) { statement ; i++; } These loops are equivalent . i = 0 statement i++ i < 10 true false
5 for loop (syntax) for ( expr1 ; expr2 ; expr3 ) statement ; next_statement; Typical use of each "expr" expr1 – initialization expr2 – condition expr3 – increment / decrement Must separate expr1 , expr2 , and expr3 using " ; " expr1 statement expr3 expr2 true false next_statement

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
6 #include <iostream> using namespace std; int main() { int count, i; cout << "Count? " ; cin >> count; cout << endl; for (i = 0 ; i < count; i++) cout << (count – i) << endl; cout << "Go!\n" ; return 0 ; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Count? 5 5 4 3 2 1 Go! for (i = count; i >= 1; i--) cout << i << endl; Alternative
7 int i; // Declaring the loop variable outside the loop for (i = 0 ; i < 5 ; i++) cout << i << endl; // i is accessible outside the for loop // Declaring the loop variable directly inside the for loop for ( int i = 0 ; i < 5 ; i++) cout << i << endl; // i is NOT accessible outside the loop Convenience, but be careful not to access the loop variable outside the loop. Note: Some compilers may allow " i " declared this way to be used outside the loop, but you should never do so.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
8 #include <iostream> using namespace std; // Calculate n factorial = n! = 1 * 2 * … * (n-1) * n
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 12/28/2010 for the course CSC CSC1110 taught by Professor Cjyuan during the Fall '06 term at CUHK.

### Page1 / 30

lec05-flow_control_2 - CSC 1111 Introduction to Computing...

This preview shows document pages 1 - 9. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online