Social Icons

Thursday, December 13, 2012

While Loop in C

While loop is one of the type of loops in C and used to repeat a block of code.

Syntax of while loop

          while (some condition)
          {
                 ---------------------
                 Some code to execute
                 ---------------------
                 increment/decrement
          }

     This loop will execute as long as the condition written in parentheses after while is correct. When the condition gets wrong, it will come out of the loop. If the condition is false in the very first then the block of code of while will not execute. Now, lets see an example of while loop using a program.

 WAP to print numbers between 1 to 100

             #include<stdio.h>
             void main()
             {
                   int  i=1;
                   while(i <= 100)
                   {
                          printf("%d \t", i);
                          i++;
                    }
               }

    Explanation:- Here, we have taken an integer variable 'i' initialized by 1. Now, it will come in while loop and will check its condition for the first time as i <= 100 means 1 <= 100. As the condition is true, it will go inside the loop and will print the value of i as 1. Again, there is an increment in i (i++). It will give one plus to the value of i. Now, i = 2. Again, it will check the condition of while as i <= 100. This time, it will check as 2 <= 100. Again, the condition is true and 2 will be printed. Similarly, it will be printed as  1 to 100. When value of i will be 101. It will check the condition as 101 <= 100. As the condition is false and it will come out of the loop.

No comments:

Post a Comment

Total Pageviews