C++ while loop

  • while loop is also used to execute a block of statement repeatedly until a certain condition gets false like for loop.
  • Like for loop it also checks the condition before executing the Loop-Body but its syntax is different from for loop.
  • It is also called as entry level looping statement because here condition is checked first then enters into the loop.
  • The basic syntax of the while loop is as follows:
  • Syntax

    while( condition)

    {

    Loop-body

    }
  • In the above syntax condition is an expression. The loop-body will be executed till the condition is true. When the condition becomes false the control of program will come outside the loop and execute the statements present after the while loop. Here is a diagram which shows the concept of while-loop:
  • loop

    Here is an example-program of while loop which prints the value from 1 to 5:

    Example

    #include<iostream.h>

    #include<conio.h>

    int main()

    {

    int i=1;

    while(i<=5)

    {

    cout<<"\n"<<i;

    i=i+1;

    }

    getch();

    return 0;

    }

    Output

    The output of the above program is as follows:

    1

    2

    3

    4

    5