Loops In C/C++ Language

While Loop in C/C++ Language

Before we use while loop statement we must Understand the While loop:
In while loop control statement, loop is executed until condition becomes false. In this loop we specify a condition (relational expression for example x>10) which give the result as True or False. The while loop executed until the condition become False.

Now if we want to print a message " Hello Learning Hints " 5 time on screen then we set a counter variable which check the number of execution and then check this counter in while loop if total number of execution are 5 then loop will be terminated.
For Example
int counter=1 ;
while(counter<=5)
{
printf("Hello Learning Hints \n") ;
counter=counter+1
}
In this example we se that as well counter remain less then or equal to 5 loop will be executed the statement in the body of loop again and again . when counter is grate the 5 then condition become false and loop will be terminated.
Syntax of for loop:
while (Test expression ) {
statements;
}

Where Test Expression is an condition (relational expression) which check that when loop will terminate. when condition becomes false loop will be terminated.

for example while (counter <=5)

Note:- (Relational expression compare two variable or constant and give the result in shape of true or false for example 10 >12 return False)
after initialization of loop for example while (counter <=5) every thing in braces or "curly brackets " { " and " } " is called body of loop will be executed the number of time of the loop.

Example :1


#include <stdio.h>
int main()
{
int counter =1;
while( counter <=5)
    {
    printf("%d \t ",counter);

counter=counter+1;
    }

return 0;
}

Result

1    2    3    4    5


Explanation of above example:
as in start counter value is 1 which is less then 5. so while loop execute the statement in body of loop.
its display the message on screen "Hello Learning hints" and increase the value of counter one time as counter=counter+1 and control again transfer to the while loop. While loop again check the condition this time value of counter is 2 so loo transfer the control again in body of loop and execute the statements and in the result counter again increase one time and control again transfer to the while loop .
This process repeated again and again until counter have a value 5 and condition become false then loop will be terminated and control transfer after the body of loop.