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

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 b The while loop has the general form while ( boolean condition ) { **STATEMENTS** } b The while loop is like a repeated if statement. b It will repeat the statements within the braces { } as long as the boolean condition is true. b But to run the loop the first time, you have to make sure that boolean condition starts out true. b 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 DocumentRight Arrow Icon
2 Sec 3.8 : The do loop b The do loop (also called do-while loop) checks the boolean condition at the end of the statements. do { **STATEMENTS** } while ( boolean condition ); b The do loop will always run at least once. b 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 b We use a do loop instead of a while loop if we want to run the code at least once. b For example, in tic-tac-toe we want to play a first game and then ask the user to play again. b For the while loop, we had to make sure the boolean condition was initially true by initializing response = “y”; b 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 b Often we want to run a loop a fixed number of times. b In a while loop, we create a counter . Usually we use a single letter, like i . i = start ; while ( i <= end ) { **STATEMENTS** i++; } b 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 b The general form of a for loop is: for ( initalization ; stopping condition ; update ) { **STATEMENTS** } b Note the semi-colons in between the 3 pieces. b
Background image of page 3

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

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

Page1 / 12

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

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online