C While Loop

The while loop in C is a pre-tested loop that executes a block of code as long as a specified condition remains true. It is ideal for situations where the number of iterations is not known in advance, as it continues looping until the condition evaluates to false.

Syntax of the while Loop in C

while (condition) {
// Code to be executed
}

Condition: The loop continues to execute as long as this condition evaluates to true. If the condition is false at the start, the loop body will not execute.

Flowchart of the while Loop

1. Condition Check: Evaluate the condition.

     • If true, proceed to execute the loop body.

     • If false, exit the loop.

2. Execution: Execute the statements inside the loop.

3. Repeat: Go back to the condition check.

Examples of the while Loop

Example 1: Print Numbers 1 to 5

#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 5) {
        printf("%d\\n", i);
        i++;
    }

    return 0;
}

Output:

1
2
3
4
5

Example 2: Print Multiplication Table

#include <stdio.h>

int main() {
    int i = 1, number;
    printf("Enter a number: ");
    scanf("%d", &number);

    while (i <= 10) {
        printf("%d x %d = %d\\n", number, i, number * i);
        i++;
    }

    return 0;
}

Output:

Enter a number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Properties of the while Loop

Conditional Expression: The loop executes as long as the condition evaluates to true. If the condition is false initially, the loop body will not execute.

Condition Expression is Mandatory: A while loop must have a condition expression. If it's omitted or incorrect, the program will either not compile or not behave as expected.

Empty Loop Body: A while loop can have an empty body, but it’s often useful to include at least a comment or continue statement to indicate intentionality.

Multiple Conditions: Multiple conditions can be combined using logical operators (e.g., &&, ||).