While Loop
Introduction to C
Structure of a C Program
Variables and Data Types
Input and Output
Operators in C
Decision Making
If Statement
if...else Statement
Nested if Statement
Nested if...else Statement
Switch Statement
Loops
For Loop
While Loop
Do While Loop
Loop Comparison
Arrays
Strings
Functions
Function Types
Library Functions
User-Defined Functions
Recursion Function
Pointers
Structures
File Handling
Common Mistakes
Ideas
While Loop
The while Loop
What is a while Loop?
The while loop is an entry-controlled loop. It repeats a block of code as long as a specified condition remains True.
Because the condition is checked before the code inside the loop runs, if the condition is False at the very start, the code block will never execute even once. This makes it perfect for situations where you don't know how many times the loop should run.
Syntax
while (condition) {
// Statements to repeat
update_expression; // Change the variable to eventually end the loop
}
// Statements to repeat
update_expression; // Change the variable to eventually end the loop
}
Practical Examples
Example 1: Basic Counter
int i = 1; while (i <= 5) { printf("Iteration: %d\n", i); i++; // Increment i to avoid an infinite loop }
Example 2: User Input Loop
int number = 1; // Keep asking for a number until the user enters 0 while (number != 0) { printf("Enter a number (0 to quit): "); scanf("%d", &number); }
The Golden Rule: Always make sure your loop body contains an update expression (like
i++ or scanf). If you forget to change the variable that the condition depends on, the condition will always be true, creating an infinite loop!
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on While Loop to test your knowledge.
Browse Quizzes »