- What a while loop is and why we use it in C programming
- How the while loop works with real examples
- Where to use while loops in real applications
- How to write a program using while loop
- Complete program examples with explanations
Introduction
In this tutorial section, we will learn what a while loop is in C programming.
A while loop is one of the most important looping constructs in C. It allows you to execute a block of code repeatedly as long as a condition remains true.
What is a while Loop in C?
A while loop in C Programming is a pre-tested loop. In general, a while loop repeatedly executes a part of the code statements multiple times, depending upon a given condition.
The while loop is also known as a pre-tested or entry-controlled loop, meaning the condition is tested before the body of the loop executes.
A while loop in C language is an iterative/repeating statement and is used when a specific statement needs to be executed again and again.
💡 Key Point: A while loop is called an entry-controlled loop because first, the boolean expression is tested, and depending on the tested result, the loop is executed.
Real-World Use Cases of while Loop
Following are some real use cases of a while loop:
- Music Player loop: While the user does NOT press 'stop' and the playlist is NOT stopped, get the next song and play the song.
- User input loop: Ask a yes-no question to the user and get an answer. While the answer is not 'yes' and the answer is not 'no', repeat the question.
- Username and password validation: Validate username and password until both are correct.
- ATM PIN validation: Keep asking for PIN until the correct PIN is entered.
Advantages of Using while Loop in C Programming
1. Simple and easy to understand — The syntax is beginner-friendly
2. Repeats execution automatically — As long as the condition remains true
3. Flexible — Can handle complex conditions and logic
Disadvantages of Using while Loop in C Programming
1. Semicolon pitfall: Placing a semicolon after a while loop's condition (e.g., while(condition);) can create a problem. Although it might compile correctly, this will make the loop an infinite loop.
2. Unexpected results: A while loop can lead to unexpected results in a C program when its exit condition is not well-defined.
3. Infinite loop risk: If the condition never becomes false, the program runs forever.
Flowchart of while Loop
The flowchart below shows how the while loop works step by step:
Step-by-step explanation:
1. Initialization: After step-by-step execution of the instructions, the program control enters the initialization part. In this step, the programmer declares or initializes the variable to some value.
Initialization of the variable happens outside the loop and it is not part of the while loop, but it is essential to initialize it before the loop starts because it is required when the programmer uses a variable in the condition or test expression.
2. Condition: The condition is an expression that may evaluate to either true or false. This is one of the primary and most essential steps, as it decides whether the block of code in the while loop will execute or not. The code inside the body of the while loop will be executed if and only if the tested condition is true; otherwise, control jumps outside the loop and stops the execution.
3. Body: It is a block of code or the actual set of statements that will be executed repeatedly until the specified condition is true. This block of code or statements is known as the body of the loop. It can include variables, functions, expressions, etc.
4. Updation: Updation is not part of the syntax, but we have to define it explicitly in the body of the loop. It is an expression that changes the value of the loop variable in each step of execution or iteration.
Syntax of while Loop in C
Let us study the real-world syntax of the while loop and then we will look in detail into all parts of the while loop.
/* statements outside loop */
/* initialization */
int i = 1;
while (condition) {
/* code inside body of loop */
/* statements to be executed */
/* update expression */
i++;
}
/* statement outside loop */
Let's break down each part:
🔹 Initialization: Variables are declared and initialized before the loop starts. This happens outside the while loop.
🔹 Condition: The condition is tested before each iteration. If true, the loop body executes. If false, the loop ends.
🔹 Body: The statements inside the loop that execute repeatedly as long as the condition is true.
🔹 Update Expression: This changes the loop control variable to ensure the loop eventually terminates.
⚠️ Important: Make sure the update expression eventually makes the condition false. Otherwise, you'll create an infinite loop.
Program to Illustrate while Loop in C
The program below displays "Inside the While loop Body" 10 times using a while loop.
#include <stdio.h>
int main() {
/* Declaration and initialization expression */
int n = 1;
/* test the expression */
while (n <= 10) {
printf("\n Inside the While loop Body");
/* update expression */
n += 1; // n++
}
return 0;
}
Sample Output:
Inside the While loop Body Inside the While loop Body Inside the While loop Body Inside the While loop Body Inside the While loop Body Inside the While loop Body Inside the While loop Body Inside the While loop Body Inside the While loop Body Inside the While loop Body
Explanation:
- The program starts from the
main()function. nis declared and initialized to 1.- The condition
while(n <= 10)is tested. Since 1 <= 10 is true:- "Inside the While loop Body" gets printed for the 1st time.
- Updation takes place:
n += 1executes, sonbecomes 2.
- The condition
while(n <= 10)is tested again. Since 2 <= 10 is true:- "Inside the While loop Body" gets printed for the 2nd time.
- Updation takes place:
n += 1executes, sonbecomes 3.
- This process continues until
nbecomes 10. - When
nis 10,10 <= 10is true:- "Inside the While loop Body" gets printed for the 10th time.
- Updation takes place:
n += 1executes, sonbecomes 11.
- The condition
while(n <= 10)is tested again. Since 11 <= 10 is false. - Control flow goes outside the loop and
return 0;stops program execution.
💻 Practice Exercise
Challenge: Write a program that asks the user to enter a number. The program should keep asking until the user enters a number greater than 100. Then display the final number.
🔍 Click to Show Solution
#include <stdio.h>
int main() {
int num;
printf("Enter a number greater than 100: ");
scanf("%d", &num);
while (num <= 100) {
printf("Try again! Enter a number greater than 100: ");
scanf("%d", &num);
}
printf("You entered: %d\n", num);
return 0;
}
📝 Summary
- A while loop is an entry-controlled or pre-tested loop
- The condition is checked before executing the loop body
- If the condition is false initially, the loop body never executes
- It is useful when the number of iterations is not known in advance
- Proper initialization, update expressions, and loop conditions are necessary to avoid infinite loops
Frequently Asked Questions About while Loop in C
1. What is the difference between while loop and do-while loop?
The main difference is that a while loop checks the condition first – if it's false, the loop never runs. A do-while loop runs the code first, then checks the condition – so it always runs at least once.
2. When should I use a while loop?
Use a while loop when you don't know how many times the loop should run, and you want to check the condition before each iteration. Examples include user input validation, reading files until EOF, and game loops.
3. Can a while loop run forever?
Yes! If the condition is always true, the loop will run forever. This is called an infinite loop. For example, if you write while(1) or forget to update the loop variable, the loop will never end.
4. What happens if the condition is false initially in while loop?
If the condition is false initially, the loop body never executes. The program skips the loop entirely and continues with the code after the loop.
5. Can I use break and continue in while loop?
Yes, you can use both break and continue in a while loop. break exits the loop immediately. continue skips the rest of the current iteration and jumps to the condition check.
💡 Tip: Always make sure the update expression changes the variable used in the condition. Otherwise, you might create an infinite loop.