0
0
Cprogramming~5 mins

While loop in C

Choose your learning style9 modes available
Introduction

A while loop helps you repeat a set of instructions as long as a condition is true. It saves you from writing the same code many times.

When you want to keep asking a user for input until they give a valid answer.
When you want to count up or down until a certain number is reached.
When you want to keep checking if a task is done before moving on.
When you want to repeat an action but don't know in advance how many times.
Syntax
C
while (condition) {
    // code to repeat
}

The condition is checked before each repetition.

If the condition is false at the start, the code inside the loop will not run at all.

Examples
This prints numbers 0 to 4 by increasing i each time.
C
int i = 0;
while (i < 5) {
    printf("%d\n", i);
    i++;
}
This counts down from 10 to 1, printing each number.
C
int count = 10;
while (count > 0) {
    printf("Countdown: %d\n", count);
    count--;
}
Sample Program

This program prints numbers from 1 to 5 using a while loop. It starts with number at 1 and keeps printing and increasing it until it reaches 5.

C
#include <stdio.h>

int main() {
    int number = 1;
    while (number <= 5) {
        printf("Number is %d\n", number);
        number++;
    }
    return 0;
}
OutputSuccess
Important Notes

Make sure to change something inside the loop that affects the condition, or the loop will run forever.

Use break; inside the loop if you want to stop it early.

Summary

A while loop repeats code while a condition is true.

The condition is checked before each repetition.

Remember to update variables inside the loop to avoid infinite loops.