Professional Documents
Culture Documents
Chapter Four
Chapter Four
– do -while
Least flexible
Always executes loop body at least once
– for
Natural "counting" loop
while Loops Syntax
The while statement (also called the while loop) provides a
way of repeating a statement while a condition holds.
while Loops
Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
– Loop body executes how many times?
while Loops Example2
void main()
{
int sum =0,i=1,n;
cout<<"Enter the maximum number"<<endl;
cin>>n;
while (i <= n)
sum += i++;
cout<<"the sum of numbers from 1 to <<n<<"is
=:"<<sum;
}
do-while Loop Syntax
The do statement (also called do loop) is similar to the while
statement, except that its body is executed first and then the
loop condition is examined.
do-while Loop
First statement is executed and then expression is evaluated.
process is repeated.
Otherwise, the loop is terminated.
count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition
Loop body executes how many times?
void main ()
{
char ch;
do
{
cout<<"Hello!\n";
cout<<"Do you want to display more Hello's (Y/N) ";
cin >>ch;
} while (ch != 'N');
}
for Loop Syntax
for(expression1;expression2;expression3)
First expression1 is evaluated. Each time round the loop,
for (count=0;count<3;count++)
{
cout << "Hi "; // Loop Body
}
How many times does loop body execute?
For Loop Example
void main ()
{
int x, limit, sum;
cout << "Please enter a number bigger than 1 : ";
cin >> limit;
sum = 0;
for (x = 1; x <= limit; x++) {
cout << "I am adding " << x << endl;
sum = sum + x;
}
cout << endl;
cout << "The sum of all the numbers from 1 to ";
cout << limit << " is " << sum;
return;
}
Converting Between For and While Loops
int i = 1;
while (i < 1024) {
cout << i << endl;
i *= 2;
}
Loop Issues
Loop’s condition expression can be ANY boolean
expression
Examples:
while (count<3 && done!=0)
{
// Do something
}
for (index=0;index<10 && entry!=-99)
{
// Do something
}
Loop Pitfalls: Misplaced ;
40