while loop in C


The simplest of all the looping structure in C is the while statement. The syntax of while format is:

while (test condition)
{
body of the loop
}


The while is an Entry Controlled loop statement. The test-condition is evaluated and if the condition is True, then the body of the loop will be executed. After the Execution of body, the test-condition is once again evaluated and if it is true the body will executed once again.
This process of repeated execution of the loop body continues until the test condition finally become False and the control is transferred out of the loop.


NOTE

  • If body of loop have more than one statement, then it is written within opening curly braces ({) and closing curly braces (}).
Example 1

Here the body of the loop is executed 10 times for n=1, 2, 3...10 where n is control variable. Each time the value on n is incremented inside the loop. And the square of n is adding in each execution of the loop. This is an example of counter-controlled loops as we know in advance how many times the loop will executed.

Example 2


Here there are four steps:

  1. Initialize the control variable p.
  2. The loop will continue until the value of (p !=5).
  3. If the value of p is 5, then the loop terminates and the control goes to the next statement.
  4. When the loop gets over, it will print “The loop is over & p=5”.

Example: Write a program to evaluate the expression b=a^n where n is positive integer.



Output:

Enter the value of a & n2
5
a= 2.000000
n=5
a to power n= 32.000000


Here the variable b is initialized to 1 and then multiplied n times by using while loop. The count is control variable, the value of count is increased inside the loop. When the value of count is greater than n than the control is over or Exits the loop.


Do You Know?