User Menu

Login



Share with

Loops in C++ PDF Print E-mail

Loops in C++

Loops have a purpose to repeat a statement a certain number of times or while a condition is fulfilled.

Loops in C++ are mainly of three types :-

'while' loop

'do while' loop

'for' loop

The while loop

while (expression)

{ statement(s) };

While Loop

and its functionality is simply to repeat statement while the condition set in expression is true.For example, we are going to make a program to countdown using a while-loop:

// custom countdown using while

#include <iostream.h>

int main ()

{
  int n;


  cout << "Enter the starting number := ";

  cin >> n;

  while (n>0) {

    cout << n << ", ";

    --n;

  }

  cout << "Finished !\n";

  return 0;

}

Enter the starting number := 8

8, 7, 6, 5, 4, 3, 2, 1, Finished!

When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true.

The whole process of the previous program can be interpreted according to the following script (beginning in main):

User assigns a value to n

The while condition is checked (n>0). At this point there are two possibilities:

*condition is true: This statement will be executed:
 cout << n << ", "; --n;

*condition is false:This statement will be executed:
 cout << "Finished!\n";return 0;

When creating a while-loop, we must always consider that it has to end at some point, therefore we must provide within the block some method to force the condition to become false at some point, otherwise the loop will continue looping forever. In this case we have included --n; that decreases the value of the variable that is being evaluated in the condition (n) by one - this will eventually make the condition (n>0) to become false after a certain number of loop iterations: to be more specific, when n becomes 0, that is where our while-loop and our countdown end.

The do-while loop

Its format is:

do
{
statement(s);
}while (condition);

do while loop

Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled.

For example, the following example program echoes any number you enter until you enter 0.

Example of do-while loop

#include <iostream.h>
int main ()
{
  long n;
  do {
    cout << "Enter any number (0 to end): ";
    cin >> n;
    cout << "You have entered: " << n << "\n";
  } while (n != 0);
  return 0;
}

Enter number (0 to end): 888
You entered: 888
Enter number (0 to end): 777
You entered: 777
Enter number (0 to end): 0
You entered: 0

The do-while loop is usually used when the condition that has to determine the end of the loop is determined within the loop statement itself, like in the previous case, where the user input within the block is what is used to determine if the loop has to end.

In fact if you never enter the value 0 in the previous example you can be prompted for more numbers forever.

The for loop

Its format is:

for (initialization; condition; increase)

{
//statement;
}

It works in the following way:

initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once.


condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed).

statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.

finally, whatever is specified in the increase field is executed and the loop gets its execution again

Here is an example of countdown using a for loop:

Example using a for loop

#include <iostream.h>

int main ()

{
  for (int n=5; n>0; n--)

{
    cout << n << ", ";

}
  cout << "Finished!\n";

  return 0;

}

5, 4, 3, 2, 1, Finished!

The initialization and increase fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written.

For example we could write: for (;n<10;) if we wanted to specify no initialization and no increase; or for (;n<10;n++) if we wanted to include an increase field but no initialization (maybe because the vriable was already initialized before).

Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example:

The comma operator (,) is an expression separator, it serves to separate more than one expression where only one is generally expected. For example, suppose that we wanted to initialize more than one variable in our loop:

for ( n=0, i=10 ; n!=i ; n++, i-- )

{
   // Statements ;

}

This loop will execute for 5 times if neither n or i are modified within the loop:

n starts with a value of 0, and i with 10, the condition is n!=i (that n is not equal to i). Because n is increased by one and i decreased by one, the loop's condition will become false after the 5th loop, when both n and i will be equal to 5.

Nested for Loop

The placing of one loop inside the body of another loop is called nesting.  When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop.

nested loop

Syntax:

The syntax for a nested for loop statement in C++ is as follows:

for ( initialisation; condition; increment )
{
   for ( initialisation; condition; increment )
   {
      statement(s);
   }
   statement(s); 
}

The syntax for a nested while loop statement in C++ is as follows:

while(condition)
{
   while(condition)
   {
      statement(s);
   }
   statement(s); 
}

The syntax for a nested do...while loop statement in C++ is as follows:

do
{
 statement(s); 
   do
   {
    statement(s);
   }while( condition );

}while( condition ) 

The following program uses a nested for loop to find the prime numbers from 2 to 50:

#include <iostream.h>

int main ()
{
int i, j;
  for(i=2; i<50; i++)

{
  for(j=2; j <= (i/j); j++)
   if(!(i%j))
     break; //if not prime
    if(j > (i/j))
      cout << i << " is prime\n";
}

return 0;
}

scroll back to top