while loop in C

Programming languages or concepts
0

A while loop in C programming repeatedly executes a target statement as long as a given condition is true. While loop is additionally referred to as a pre-tested loop. In general, a long time loop allows a component of the code to be executed multiple times depending upon a given boolean condition. It are often viewed as a repeating if statement. The while loop is generally utilized in the case where the amount of iterations isn't known before. The while loop loops through a block of code as long as a specified condition is true.

Syntax of while loop in C language

 Syntax 
The syntax of a long time loop in C programing language is − 
do {
  // code block to be executed
}
while (condition);


 could also be one statement or a block of statements. The condition could also be any expression, and true is any nonzero value. The loop iterates while the condition is true.

Flowchart of while loop in C

While loop in c


Properties of while loop

     A conditional expression is employed to test the condition. 
    The statements defined inside the while loop will repeatedly execute until the given condition fails. o The condition are true if it returns 0. The condition are going to be false if it returns any non-zero number. 
     In while loop, the condition expression is compulsory. 
     Running ages loop without a body is feasible. 
     We can have quite one conditional expression in while loop. 
     If the loop body contains only 1 statement, then the braces are optional.

    Example while loop in C

    #include <stdio.h>

    int main() {
      int i = 0;
      
      while (i < 10) {
        printf("%d\n", i);
        i++;
      }
      
      return 0;
    }

    Output


    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

    #include <stdio.h>

    int main()
    {
    // initialization expression
    int i = 1;

    // test expression
    while (i <= 10) {
    printf("Hello World\n");

    // update expression
    i++;
    }

    return 0;
    }


    Output

    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World
    Hello World


    Infinitive while loop in C
     If the expression passed in while loop ends up in any non-zero value then the loop will run the infinite number of times. 

    While(1)
    {
       // Statement:
    }

    Example Infinitive while loop in C


    #include<stdio.h>  
    void main ()  
    {  
        int x = 10, y = 2;  
        while(x+y-1)  
        {  
            printf("%d %d",x--,y--);  
        }  

    Output

    infinite loop 

    Post a Comment

    0Comments

    Post a Comment (0)
    close