In C programming, the while loop is used to repeatedly execute a block of code as long as a given condition is true.
It’s particularly useful for cases where you don’t know beforehand how many times the loop should run, as it will keep looping until the condition becomes false.
1. Basic Syntax of the while Loop
while (condition) { // Code to be executed repeatedly }
- Condition: The while loop will keep executing as long as this condition is true.
- Loop body: Code inside the curly braces {} that runs on each iteration of the loop.
If the condition is false initially, the loop body will not execute at all.
2. Basic Example of while Loop
Let’s start with a simple example where we use a while loop to print numbers from 1 to 5.
#include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("%d\n", i); i++; // Increment i to avoid an infinite loop } return 0; }
Explanation:
- i is initialized to 1.
- The while loop checks if i is less than or equal to 5.
- Inside the loop, i is printed, and then incremented by 1 to eventually terminate the loop.
Output:
1 2 3 4 5
3. while Loop with a Counter
A counter variable is often used in loops to control how many times the loop should execute.
#include <stdio.h> int main() { int counter = 10; while (counter > 0) { printf("Counter: %d\n", counter); counter--; // Decrement counter by 1 on each iteration } return 0; }
Explanation:
- counter starts at 10.
- Each iteration decrements counter by 1 until it reaches 0, where the condition counter > 0 becomes false, and the loop stops.
Output:
Counter: 10 Counter: 9 Counter: 8 Counter: 7 Counter: 6 Counter: 5 Counter: 4 Counter: 3 Counter: 2 Counter: 1
4. Infinite while Loop
An infinite loop occurs when the condition never becomes false, causing the loop to execute endlessly. This can happen if there is no code to modify the condition or if the condition always remains true.
#include <stdio.h> int main() { int i = 1; while (1) { // Always true printf("Infinite loop, i = %d\n", i); i++; if (i > 5) { break; // Breaks the loop when i becomes greater than 5 } } return 0; }
Explanation:
- while (1) creates an infinite loop because 1 (true) never changes.
- Inside the loop, we use if (i > 5) break; to exit the loop when i exceeds 5.
Output:
Infinite loop, i = 1 Infinite loop, i = 2 Infinite loop, i = 3 Infinite loop, i = 4 Infinite loop, i = 5
5. while Loop with User Input
The while loop can also be used to repeatedly ask for user input until a specific condition is met.
#include <stdio.h> int main() { int number; printf("Enter numbers until you enter -1 to stop:\n"); while (1) { scanf("%d", &number); if (number == -1) { break; // Exit the loop if user enters -1 } printf("You entered: %d\n", number); } printf("Loop ended.\n"); return 0; }
Explanation:
- The while loop continuously asks for user input.
- If the user enters -1, the break statement exits the loop.
- This technique is useful for processing an indefinite number of inputs.
Sample Output:
Enter numbers until you enter -1 to stop: 5 You entered: 5 10 You entered: 10 -1 Loop ended.
6. Summing Numbers Using while Loop
The while loop can be used to calculate the sum of a series of numbers.
#include <stdio.h> int main() { int sum = 0; int number = 1; while (number <= 10) { sum += number; number++; } printf("The sum of numbers from 1 to 10 is: %d\n", sum); return 0; }
Explanation:
- number starts at 1 and increments up to 10.
- Each iteration adds number to sum.
- After the loop, sum contains the total of all numbers from 1 to 10.
Output:
The sum of numbers from 1 to 10 is: 55
7. Nested while Loops
A while loop can be nested inside another while loop. This is useful for working with multi-dimensional data, such as matrices.
Example: Printing a 3×3 Matrix
#include <stdio.h> int main() { int i = 1; while (i <= 3) { int j = 1; while (j <= 3) { printf("%d ", j); j++; } printf("\n"); i++; } return 0; }
Explanation:
- The outer while loop iterates over the rows (i).
- The inner while loop iterates over the columns (j), printing numbers in a 3×3 grid.
Output:
1 2 3 1 2 3 1 2 3
8. Calculating Factorial Using while Loop
The while loop can be used to calculate the factorial of a number.
#include <stdio.h> int main() { int num = 5; int factorial = 1; int i = 1; while (i <= num) { factorial *= i; i++; } printf("Factorial of %d is: %d\n", num, factorial); return 0; }
Explanation:
- factorial starts at 1 and is multiplied by each integer up to num.
- After the loop completes, factorial contains the factorial of num.
Output:
Factorial of 5 is: 120
9. Validating User Input with while Loop
The while loop is useful for input validation, allowing you to prompt the user until valid input is provided.
#include <stdio.h> int main() { int age; printf("Enter your age (1-120): "); scanf("%d", &age); while (age < 1 || age > 120) { printf("Invalid age! Please enter a valid age (1-120): "); scanf("%d", &age); } printf("Your age is: %d\n", age); return 0; }
Explanation:
- If the user enters an age outside the range 1–120, the while loop asks for input again.
- The loop continues until a valid age is entered.
Sample Output:
Enter your age (1-120): -5 Invalid age! Please enter a valid age (1-120): 130 Invalid age! Please enter a valid age (1-120): 25 Your age is: 25
10. Summary Table of while Loop Examples
Use Case | Description | Example Code |
---|---|---|
Basic counter | Print numbers from 1 to 5 | while (i <= 5) { … } |
Infinite loop | Repeat endlessly until break condition | while (1) { if (i > 5) break; } |
User input loop | Loop until a certain input is provided | while (1) { scanf(…); if (…) break; } |
Summing numbers | Calculate total sum of a sequence of numbers | while (i <= 10) { sum += i; i++; } |
Nested loop | Create 2D pattern or grid | while (i <= 3) { while (j <= 3) { … } } |
Factorial calculation | Multiply numbers up to n | while (i <= num) { factorial *= i; } |
Input validation | Re-prompt user until valid input | `while (age < 1 |
Complete Example: Multiple Uses of while Loop
This example demonstrates the while loop’s versatility by incorporating counting, summing, and checking user input.
#include <stdio.h> int main() { int sum = 0; int number; printf("Enter numbers to add (0 to stop):\n"); while (1) { printf("Enter a number: "); scanf("%d", &number); if (number == 0) { break; // Stops the loop if 0 is entered } if (number < 0) { printf("Negative numbers are ignored.\n"); continue; // Skips adding negative numbers } sum += number; } printf("Total sum of positive numbers: %d\n", sum); return 0; }
Explanation:
- The while (1) loop continually asks the user for a number.
- Entering 0 stops the loop (break).
- Negative numbers are ignored with continue, while positive numbers are added to sum.
Sample Output:
Enter numbers to add (0 to stop): Enter a number: 5 Enter a number: -3 Negative numbers are ignored. Enter a number: 10 Enter a number: 0 Total sum of positive numbers: 15
The while loop is a powerful construct in C for managing repetitive tasks.