C while Loop

Summary: in this tutorial, you will learn about the C while loop statement to execute 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:

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

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.

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 exceed 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.