An Iteration involves repeating some portion of a program, a specified number of time or until a particular condition is satisfied. This repetitive operation in C and C++ is achieved through for, while and dowhile loop.

How does a for loop work?

A for loop is the easiest iteration loop to understand the C and C++ loops. All the loop elements are gathered at one place unlike the other loops, where, the loop elements are scattered all over the loop body.

Syntax:

E.g.:

  • Initialization: In the above example, initialization is i=0, the value of i will determine till what time the loop will run. As long as i, in this case, remain less than 5, the loop will run.
  • Condition: This will check for the condition to be true. In the above example, the loop will check the value of i to be less than 5 and if the condition is true, the loop body will execute.
  • Increment or Decrement : This statement increments or decrements the value of i. If the value of i is not incremented or decremented, the for loop can go into an infinite iteration.

A for loop can also have multiple initialization, condition checks and increment decrement operators, but they all must be separated by commas.

E.g.:

How does a while loop work?

The second loop available, is the while loop which is an entry controlled loop. An entry controlled loop is one in which the condition check is done before the execution of the loop body. Where as a dowhile loop is an exit controlled loop in which the condition check is done after the execution of the loop body (we will learn more about do-while loop at later)

Syntax:

Example:

The above program prints the first 10 natural numbers using a while loop. In case of a for loop, the initialization, condition check and increment were all in the same line, while

In while loop, it is scattered over the program.

  • int i=0 is the initialization
  • i<=10 is the condition check
  • i++ is the increment

Example 2: Program to calculate factorial of a number

The above program allows the user to input a number and print the factorial of that number using a while loop.

How does a do-while loop work?

As mentioned earlier, the dowhile loop, unlike a while loop, is an exit controlled loop which means that, it evaluates the test condition after executing the loop body statements. It implies that the dowhile loop executes at least once before the test condition will be evaluated.

The loop body will execute at least once even if the test condition is false, where as the same would not happen in while loop.

Syntax:

Example:

The above program shows the execution of exit controlled loop, dowhile, which prints the alphabets from A to M. Here the test condition is tested after the execution of the loop body.

dowhile loops are used for making menu driven programs where the menu should be displayed at least once before the loop body is executed.