C While Loop

A loop repeats a block of code many times. The while loop checks the condition first, and runs the body while it is true. Use it when you do not know how many times to repeat.

Syntax

while (condition) {
    // code to repeat
}

Print numbers 1 to 5

#include <stdio.h>

int main(void) {
    int i = 1;

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

Output:

Output of the above program is

1
2
3
4
5

The three steps are: set the start value (i = 1), check the condition (i <= 5) and change the value (i++). If you forget the last step, the loop never ends.

Sum of digits of a number

#include <stdio.h>

int main(void) {
    int n = 4825, sum = 0;

    while (n > 0) {
        sum += n % 10;   // last digit
        n /= 10;         // remove last digit
    }
    printf("Sum = %d\n", sum);
    return 0;
}

Output:

Output of the above program is

Sum = 19

Infinite loop

A condition which is always true makes a loop that never stops. We stop it with break.

#include <stdio.h>

int main(void) {
    int count = 0;

    while (1) {
        count++;
        if (count == 3) break;
    }
    printf("Stopped at %d\n", count);
    return 0;
}

Output:

Output of the above program is

Stopped at 3

Note: If the condition is false at the start, the body of a while loop does not run even one time.

Next: C Do While Loop.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to check whether a number is even or odd
Write a C program to check whether a user is eligible to vote or not
Write a C program to check whether an alphabet is vowel or consonant
Write a C program to find the maximum number between three numbers
Write a C program to check whether a number is positive, negative or zero
Write a C program to calculate an electricity bill
Write a C program to print 1 to 10 numbers using a while loop
Interview Questions & Answers
What is the difference between while and do while loop in C?
What is the difference between break and continue in C?
How to check if a number is prime in C?
How to find the factorial of a number in C?