while Loop


    while Loop is also entry controlled loop. The difference between for Loop and while Loop is that we need to declare and initialize the variable outside the Loop and we need to increment or decrement the value inside the Loop. Let's have a look at while Loop's syntax.
    
    declaration and initialization of variable;
    while ( condition )
    {
     // Codes inside while Loop
     increment/decrement
    }
    
    Here, in while Loop, we need to declare the variable and also initialize it before the Loop. We need to specific the condition and the Loop works until the condition is satisfied. Inside the Loop only, we need to increment or decrement the variable. So, the while Loop works like this : condition is checked, if true, then the block of code inside loop will execute and inside the block of code, the increment or decrement is done. If the conditon is break, the compiler comes to next line of code after the Loop.
    
    Let's now understand while Loop with an example. Example is of printing hello 5 times.
    
    #include <stdio.h>
     int main()
     {
        int i=1;
        while(i<=5)
        {
            printf("Hello\n");
            i++;
        }
        return 0;
     }
    
    
    
    Explaination of the program :
    As we are using while Loop in this program, we need to declare and initialize the variable first, as we did, declaring and initializing to 1. Now the condition for while Loop is i <= 5 ( i less than or equal to 5 ). If the condition satisfies, then the compiler will execute the block of code inside the while Loop i.e will print Hello and then increment the value of i. \n means breaking of line. The Compiler will again move to condition and check if satisfies then again it will execute the block of code and increment will be done and the same step will be repeated until the condition gets break. Once break, the compiler will jump to next line of code after while Loop.
    Previous
    Next Post »
    0 Comment