Loops: © 2004 Pearson Addison-Wesley. All Rights Reserved 5-1
Loops: © 2004 Pearson Addison-Wesley. All Rights Reserved 5-1
while ( condition )
statement;
condition
evaluated
true false
statement
int count = 1;
while (count <= 5)
{
cout<<count;
count++;
}
true
product <= 1000 product = 2 * product
false
int x = 1;
while (x < 10) {
cout<<x;
x++;
}
• Label the following loop
int product = 2;
while ( product <= 1000 )
product = 2 * product;
• The body of a while loop eventually must make the condition false
• If not, it is called an infinite loop, which will execute until the user
interrupts the program
• This is a common logical error
• You should always double check the logic of a program to ensure that
your loops will terminate normally
int count = 1;
while (count <= 25)
{
System.out.println (count);
count = count - 1;
}
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
cout<<“Here";
count2++;
}
count1++;
}
do
{
statement;
}
while ( condition )
statement
true
condition
evaluated
false
int count = 0;
do
{
count++;
cout<<count;
} while (count < 5);
statement
condition
evaluated
true
condition
true false
evaluated
statement
false
initialization
condition
evaluated
true false
statement
increment
• How many times is the following loop body repeated? What is printed
during each repetition of the loop body and after exit?
x = 3;
for (int count = 0; count < 3; count++)
{
x = x * x;
cout<<x;
}
//---------------------------------------------------
// Prints a triangle shape using asterisk (star)
// characters.
//---------------------------------------------------
void main (String[] args)
{
int MAX_ROWS = 10;