Home » Learn C Programming from Scratch » C while Loop
C while Loop
Summary : in this tutorial, you will learn how to use the C while loop statement to execute a code block repeatedly based on a condition.
Introduction C while loop statement
The C while loop statement allows you to execute a code block repeatedly based on a condition that is checked at the beginning of each iteration.
Here’s the syntax of the while loop statement:
How it works:
The while statement first evaluates the expression . If the result is non-zero ( true ), the while statement executes the statement within its body. This cycle continues until the expression becomes zero (or false ).
The while statement re-checks the expression at the beginning of each iteration before executing the statement . Therefore, at some point, the expression needs to become zero (or false ) to end the loop. Otherwise, you’ll have an indefinite loop.
When the while statment is first encountered and the expression is zero (or false ), the while statement won’t execute the statement at all. The program pass the control to the statement that follows the while statement.
The following flowchart illustrates how while loop works:
C while loop examples
Let’s take some examples of using the while loop statement
1) Simple C while loop statement
The following example uses the while loop statement to display five numbers from 0 to 4:
How it works.
- First, declare the n variable and initialize it to 0 .
- Second, check if n is less than 5 before entering the loop.
- Third, display n and add 1 to it in each iteration. Repeat this cycle until n is not less than 5 .
Since n starts with zero, the while statement executes 5 iterations.
2) Using the C while loop to develop a number guessing game
The following example illustrates how to use the while loop statement to create the number guessing game:
First, define the maximum of guesses:
Second, generate a random number between 0 and 10:
Third, allow users to prompt a number until the number of guesses reaches MAX_GUESS or the number equals the secret_number:
Fourth, increase the guess and prompt for an input:
Fifth, display a success message if the input number matches the secret number:
Sixth, show a message to the users if the number is lower or higher:
Seventh, display the remaining guesses or a failed message if the guesses have been used:
- Use the C while loop statement to repeatedly execute a code based on a condition checked at the beginning of each iteration.
IMAGES
VIDEO