Summary: in this tutorial, you will learn about the C while loop statement to execute a block of code repeatedly with a condition that is checked at the beginning of each iteration.
Introduction C while loop statement
The C while
loop is used when you want to execute a block of code repeatedly with a checked condition before making an iteration.
If you want to check the condition after each iteration, you can use do while loop statement.
The syntax of C while
loop is as follows:
1 2 3 | while (expression) { // execute statements } |
The while
loop executes as long as the given logical expression evaluates to true
. When expression evaluates to false
, the loop stops. The expression is checked at the beginning of each iteration. The execute statements inside the body of the while
loop statement are not executed if the expression evaluates to false
when entering the loop. It is necessary to update the loop condition inside the loop body to avoid an indefinite loop.
The following flowchart illustrates the while
loop in C:

C while loop flowchart
If you want to escape the loop without waiting for the expression to evaluate, you can use the break statement. If you want to go back to the top of the while loop statement without executing the code below a certain point inside the while loop body, you use the continue statement.
Example of C while loop
The following example is the number guessing game that demonstrates how to use the C while loop statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <stdio.h> #include <stdlib.h> #include <time.h> #define ALLOWED_TIMES 4 int main() { int secret, input = 0; int times = 1; /* get a random number between 0 and 10 */ srand((unsigned int)time(NULL)); secret = rand() % 10 + 1; /* start the game */ printf("--- Demonstrate C while loop statement --- \n\n"); printf("--- Number Guessing Game --- \n"); while(input != secret && times <= ALLOWED_TIMES ) { printf("Please enter a number (0 - 10):\n"); scanf("%d",&input); if(input == secret) printf("Bingo! you got it.\n"); else if(input > secret) printf("No, it is smaller.\n"); else printf("No, it is bigger.\n"); times++; } if(times == ALLOWED_TIMES) { printf("You lose! The secret number is %d",secret); } return 0; } |
How it works.
- First, it generates a secret number that is a random number between 0 and 10.
- Second, it asks the user to enter a number and matches it with the secret number. If the number of guesses exceeds the allowed guesses and the numbers that the user provided do not match, he loses, otherwise he wins.
In this tutorial, you have learned how to use C while loop statement to execute a block of code repeatedly with a checked condition at the beginning of each iteration.