While Statement

The while statement in C is used to create a loop that repeatedly executes a block of code as long as a given condition is true. It's one of the most basic forms of looping in C.

while Syntax


while (condition) {
    // Code to execute while the condition is true
}

How It Works:

Example:1


#include <stdio.h>
int main() {
    int i = 0;
    while (i < 5) {
        printf("%d\n", i);
        i++;
    }
    return 0;
}

Output

0
1
2
3
4

Example 2:Sum of Natural Numbers


#include <stdio.h>
int main() {
    int n, sum = 0, i = 1;
    printf("Enter a positive integer: ");
    scanf("%d", &n);

    while (i <= n) {
        sum += i;  // Add i to the sum
        i++;
    }

    printf("The sum of first %d natural numbers is %d\n", n, sum);

    return 0;
}

Output

Enter a positive integer: 5 The sum of first 5 natural numbers is 15

Example 3: Infinite Loop


#include <stdio.h>
int main() {
    while (1) {
        printf("This is an infinite loop.\n");
    }
    return 0;
}

Output

The loop continues until interrupted manually (e.g., using Ctrl + C).