Control Structures : Repetition
Three repetition structures are:
i) while loop
ii) do-while loop
iii) for loop
This section discusses the first looping structure, called a while loop.
1) While Loop:
The general form of the while statement is:while (expression){
statements
}
In C++, while is a reserved word. Of course, the statement can be either a simple or compound statement. The expression acts as a decision maker and is usually a logical expression. The statement is called the body of the loop. Note that the parentheses around the expression are part of the syntax.
The given Figure shows the flow of execution of a while loop.
The expression provides an entry condition to the loop. If it initially evaluates to true, the statement executes. The loop condition—the expression—is then reevaluated. If it again evaluates to true, the statement executes again. The statement (body of the loop) continues to execute until the expression is no longer true. A loop that continues to execute endlessly is called an infinite loop. To avoid an infinite loop, make sure that the loop’s body contains statement(s) that assure that the entry condition—the expression in the while statement—will eventually be false.
The next example, asks the user to enter a series of numbers. When the number entered is 0, the loop terminates. Notice that there’s no way for the program to know in advance how many numbers will be typed before the 0 appears; that’s up to the user.
#include <iostream>
using namespace std;
int main()
{
int n = 99; // make sure n isn’t initialized to 0
while( n != 0 ) // loop until n is 0
cin >> n; // read a number into n
cout << endl;
return 0;
}
Here’s some sample output. The user enters numbers, and the loop continues until 0 is entered, at which point the loop and the program terminate.
1
27
33
144
9
0
Comments
Post a Comment