Session_5 - Lesson 7: Controlling Program Flow Use of goto...

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

View Full Document Right Arrow Icon
Lesson 7: Controlling Program Flow Use of goto shown below. You are not supposed to use goto: #include <iostream> using namespace std; int main() { int counter = 0; loop: counter++; cout << "counter: " << counter << endl; if (counter < 5) goto loop; cout << "Complete. Counter: " << counter << endl; return 0; } Using goto is almost always a case of bad design. while Loops A while loop causes your program to repeat a sequence of statements as long as the starting condition remains true. #include <iostream> using namespace std; int main() { int counter = 0; while (counter < 5) { counter++; cout << "Counter: " << counter << endl; } cout << "Complete. Counter: " << counter << endl; return 0; } The condition of the while is tested and as long as it is true, the body of the while loop is executed. The formal syntax for a while statement is: while (condition) statement; The condition is any C++ expression, and statement is any valid C++ statement or block of statements. When condition evaluates true(i.e., = 1), statement is executed and then condition is tested again. This continues until condition tests false, at which time the while loop terminates and execution continues on the first line below statement . Page 1 of 9
Background image of page 1

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

View Full DocumentRight Arrow Icon
More Complicated while Statements #include <iostream> using namespace std; int main() { unsigned short small; unsigned long large; const unsigned short MAXSMALL=65535; cout << "Enter a small number: "; cin >> small; cout << "Enter a large number: "; cin >> large; cout << "small: " << small << ". ..\n"; // for each iteration, test three conditions while { if (small % 500 == 0) cout << small << endl; small++; large -=2; } cout << "\nSmall: " << small << " Large: " << large << endl; return 0; } Continue and break If you want to return to the top of a while loop before the entire set of statements is executed, you use the continue statement. Also, if you want to exit the loop when exit conditions are met you use the break statement. #include
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 9

Session_5 - Lesson 7: Controlling Program Flow Use of goto...

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

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