C While Loop

In C programming language, the while loop is used to execute a block of code repeatedly as long as a particular condition is true. The syntax of the while loop is as follows:

 
while (condition) {
    // code to be executed repeatedly
}

The condition is checked before every iteration of the loop, and if it is true, the code inside the loop is executed. This continues until the condition becomes false, at which point the loop terminates and control is passed to the next statement following the loop.

Here is an example of a while loop that prints the numbers from 1 to 5:

#include <stdio.h>

int main() {
    int i = 1;
    while (i <= 5) {
        printf("%d ", i);
        i++;
    }
    return 0;
}
 

In this example, the variable i is initialized to 1 before the while loop. The condition i <= 5 is checked before each iteration of the loop, and as long as it is true, the code inside the loop is executed. The code inside the loop prints the value of i, and then increments it using the i++ statement. This continues until i reaches 6, at which point the condition i <= 5 becomes false and the loop terminates. The program then exits with a return value of 0.

Comments

Leave a Reply

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

13731