Page 45 - DCAP404 _Object Oriented Programming
P. 45
Object-oriented Programming
Notes cout <, endl << “ Vowel u” << endl;
else
cout << endl << “ The character is not a Vowel” << endl;
return o;
}
2.4.2 Looping
The while statement is used to carry out operations, in which a group of statements is executed
repeatedly, till a condition is satisfied.
The general form of the while statement is:
while (expression) statement;
The statement will be executed repeatedly, as long as the expression is true (i.e., as long expression
has a nonzero value). This statement can be simple or compound, through it is usually a compound
statement. It must include some feature that eventually alters the value of the expression, thus
providing a stopping condition for the loop.
Did u know? What is the common error while using the while loop?
A common error when using the while loop is to forget to do anything that might change
the value being tested on while statement from within the loop. If the variable being
tested is not changed within the loop then the condition will either never be true and the
loop will therefore never get executed or it will always be true and will execute forever.
Consecutive Integer Quantities
In this example, we try to display the consecutive digits 0,1,2, . . . . 9.
# include < iostream.h >
main ( ) / * display the integers 0 through 9 * /
{
int digit =0;
while ( digit < = 9)
{
cout<<digit<<endl;
++ digit;
}
}
Initially, a digit is assigned a value of 0. The while loop then displays the current value digit,
increase its value by 1 and then repeats the cycle, until the value of digit exceeds 9. The net effect
is that the body of the loop will be repeated 10 times, resulting in 10 consecutive lines of output.
Each line will contain a successive integer value, beginning and ending with 9. Thus, when the
program is executed, the following output will be generated.
38 LOVELY PROFESSIONAL UNIVERSITY