loop and their types

loop

When we want to execute a statement or set of statement in a program to a certain number, then we use the loop statement for it. A statement in the loop continues to be repeat until the given value is false. The statement which repeat is called the body of loop, there are 3 types of looping statements in c ++.

Which are as follows:

Type of loop in C++

There are three components of a loop – variable initialization, expression / condition and value updation

 

for loop

In the for loop, there is first variable initialization, then the condition is given. If condition is true then body of loop is execute then there is an update or increment in the expression value. This sequence moves until the value of the expression is false. As soon as the condition is false, the loop gets terminated and the execution comes out of the loop on the next statement (if available).

SYNTEX-

for( initialization, expression, updation)
   {
      Body of loop;
   }

for-loop

Here is the program,

#include<iostream.h>
#include<conio.h>

  void main()
  {
   clrscr();
   int x;

    cout<<"Enter number: ";
    cin>>x;

     for(int i=0; i<5; i++)
      {
        cout<<x<<" "; // body of loop
      }

  getch();
 }
OUTPUT:-
3  3   3  3  3

In this program for-loop will work as,

 

for-program

explanation

First, input value 3 is given by the user, then goes to execution for loop where we have assigned value 0 to a variable i.

After this condition check is done because the condition is true (0<5),

so execution goes directly to the next statement and print/execute the value of the x variable, followed by expression value in increment i

Then the condition is checked, this condition will be condition (1<5), which is again true and again print the value of variable x.

This sequence moves until the condition is false (5<5). because here condition is being true five times, so here the input value (3) will printed five times

Here is procedure, 

when i =0

for-loop-step-one

when i=1

for-loop-step-two

when i =2

for-loop-step-three

when i=3

for-loop-step-three

when i=4

for-loop-step-five

Thus a successful execution of the loop is done.

The table below shows the implementation of for loop. Here, every time the initialization is incremented in value 0, then the body of loop is executed.

increment in initialization value(i=0) condition body of loop execute
0 0<5 (True) 3
1 1<5 (True) 3
2 2<5 (True) 3
3 3<5 (True) 3
4 4<5 (True) 3
5 5<5 (False) can’t execute

 

Related Exercise


previous-switch Statement

next- while-loop