{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lec10 - Lecture 10 for do and switch PIC 10A Todd Wittman...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
1 Lecture 10: for, do, and switch PIC 10A Todd Wittman Recall the while Loop box4 The while loop has the general form while ( boolean condition ) { **STATEMENTS** } box4 The while loop is like a repeated if statement. box4 It will repeat the statements within the braces { } as long as the boolean condition is true. box4 But to run the loop the first time, you have to make sure that boolean condition starts out true. box4 Sometimes we want to always execute the loop at least once.
Background image of page 1

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

View Full Document Right Arrow Icon
2 Sec 3.8 : The do loop box4 The do loop (also called do-while loop) checks the boolean condition at the end of the statements. do { **STATEMENTS** } while ( boolean condition ); box4 The do loop will always run at least once. box4 Note the semi-colon after the while. (In the standard while loop, that semi-colon would have caused big problems.) The Tic-Tac-Toe Game box4 We use a do loop instead of a while loop if we want to run the code at least once. box4 For example, in tic-tac-toe we want to play a first game and then ask the user to play again. box4 For the while loop, we had to make sure the boolean condition was initially true by initializing response = “y”; box4 The do loop doesn’t need to initialize the response string. string response = “y”; string response; while (response == “y”) { do { **Play Tic-Tac-Toe** **Play Tic-Tac-Toe** cout << “Again? (y/n)”; cout << “Again? (y/n)”; cin >> response; cin >> response; } } while (response == “y”);
Background image of page 2
3 Sec 3.7 : The for loop box4 Often we want to run a loop a fixed number of times. box4 In a while loop, we create a counter . Usually we use a single letter, like i . i = start ; while ( i <= end ) { **STATEMENTS** i++; } box4 This same loop can be written as a for loop . for (int i = start ; i <= end ; i++) { **STATEMENTS** } Initialization Stopping condition Update The for Loop box4 The general form of a for loop is: for ( initalization ; stopping condition ; update ) { **STATEMENTS** } box4 Note the semi-colons in between the 3 pieces.
Background image of page 3

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

View Full Document Right Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}