While Loops in C programming language

In C programming language the while loop is one of the decision making and looping statements. It is the simplest of all the looping structures in C programming language. The while loop is an entry controlled loop statement.  In this the test condition is evaluated at the entry and if the condition is true, then the body of the loop is executed. After execution of the body, the test-condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test-condition finally becomes false and the control is transferred out of the loop. On exit, The program continues with the statement immediately after the body of the loop.The general form of while format is –

while (test condition)
{
        body of the loop
}

The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. However, it is good practice to use braces even if the body has only one statement because C programming language is a structured language. Below is the sample C program to show the example of the while loop –

void main()
{
     int n,sum;
     
     sum=0;
     n=1;                       /*Initialization*/
     
     while(n<=10)               /*Testing*/
     {
             sum=sum+n;
             n++;                /*Incrementing*/
     }
     
     printf("sum = %d",sum);
     getch();
}

Execution Table of The above While loop C Program

Initialization n Testing n>=10 sum = sum + n n++
1 True 0+1 = 1 1+1 =2
2 True 1+2 = 3 2+1 =3
3 True 3+3 = 6 3+1 =4
4 True 6+4 = 10 4+1 =5
5 True 10+5 = 15 5+1 =6
6 True 15+6 = 21 6+1=7
7 True 21+7 = 28 7+1=8
8 True 28+8 = 36 8+1=9
9 True 36+9 = 45 9+1=10
10 True 45+10 = 55 10+1=11
11 False Won’t execute Won’t execute

So you can see that the body of the loop is executed 10 times for n=1 ,2,…. 10, each time adding the value of n to sum, which is incremented inside the loop. When the n becomes 11 after incrementing then the test condition becomes false and therefore body of the loop is not executed and the control is sent to the further statements and hence the result is shown in the next statement. The output is 55. The test condition may also be written as n<11; the result would be the same. This is the typical example of counter – controlled loops. The variable n is called counter or counter variable.

yashan has written 70 articles

One thought on “While Loops in C programming language

Cancel reply

Leave a Reply to Amit Mishra

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>