Introduction to While Loops
The while loop is a fundamental control structure in C that repeatedly executes a block of code as long as a specified condition is true. It's essential for tasks that require repetition, such as processing data streams, implementing game loops, or waiting for user input.
Basic While Loop Syntax
while (condition) {
// code to be executed
// update condition variable
}
Simple While Loop Example
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5) {
printf("Count: %d\n", count);
count++; // Increment counter
}
printf("Loop finished!\n");
return 0;
}
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Loop finished!
While Loop Flow Diagram
Start | V ┌─────────────┐ │ Initialize │ │ counter │ └─────────────┘ | V ┌─────────────┐ │ Check │──────No──────┐ │ Condition │ │ └─────────────┘ │ | │ Yes │ | │ V │ ┌─────────────┐ │ │ Execute │ │ │ Loop Body │ │ └─────────────┘ │ | │ V │ ┌─────────────┐ │ │ Update │ │ │ Counter │ │ └─────────────┘ │ | │ └───────────────────────┘ | V End
While Loop Variations
1. Countdown Loop
#include <stdio.h>
int main() {
int countdown = 10;
printf("Launch countdown:\n");
while (countdown > 0) {
printf("%d... ", countdown);
countdown--;
}
printf("LIFTOFF!\n");
return 0;
}
Output:
Launch countdown: 10... 9... 8... 7... 6... 5... 4... 3... 2... 1... LIFTOFF!
2. Sum of Numbers
#include <stdio.h>
int main() {
int n = 1;
int sum = 0;
int limit = 10;
while (n <= limit) {
sum += n;
printf("Adding %d, sum = %d\n", n, sum);
n++;
}
printf("\nSum of numbers 1 to %d = %d\n", limit, sum);
return 0;
}
Output:
Adding 1, sum = 1 Adding 2, sum = 3 Adding 3, sum = 6 Adding 4, sum = 10 Adding 5, sum = 15 Adding 6, sum = 21 Adding 7, sum = 28 Adding 8, sum = 36 Adding 9, sum = 45 Adding 10, sum = 55 Sum of numbers 1 to 10 = 55
3. Factorial Calculation
#include <stdio.h>
int main() {
int num = 5;
int factorial = 1;
int i = 1;
printf("Calculating %d!:\n", num);
while (i <= num) {
factorial *= i;
printf("%d! = %d\n", i, factorial);
i++;
}
printf("\nFinal result: %d! = %d\n", num, factorial);
return 0;
}
Output:
Calculating 5!: 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 Final result: 5! = 120
Common While Loop Patterns
1. User Input Validation
#include <stdio.h>
int main() {
int age;
int valid = 0;
while (!valid) {
printf("Enter your age (1-120): ");
scanf("%d", &age);
if (age >= 1 && age <= 120) {
valid = 1;
printf("Valid age entered: %d\n", age);
} else {
printf("Invalid age! Please try again.\n");
}
}
return 0;
}
Sample Run:
Enter your age (1-120): 150 Invalid age! Please try again. Enter your age (1-120): -5 Invalid age! Please try again. Enter your age (1-120): 25 Valid age entered: 25
2. Menu-Driven Program
#include <stdio.h>
int main() {
int choice = 0;
while (choice != 4) {
printf("\n=== MENU ===\n");
printf("1. Option 1\n");
printf("2. Option 2\n");
printf("3. Option 3\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
if (choice == 1) {
printf("You selected Option 1\n");
} else if (choice == 2) {
printf("You selected Option 2\n");
} else if (choice == 3) {
printf("You selected Option 3\n");
} else if (choice == 4) {
printf("Exiting...\n");
} else {
printf("Invalid choice! Try again.\n");
}
}
return 0;
}
3. Reading Files Until EOF
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
char line[100];
int lineNum = 1;
while (fgets(line, sizeof(line), file) != NULL) {
printf("Line %d: %s", lineNum++, line);
}
fclose(file);
return 0;
}
4. Processing Arrays
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
int i = 0;
int sum = 0;
printf("Array elements: ");
while (i < size) {
printf("%d ", numbers[i]);
sum += numbers[i];
i++;
}
printf("\nSum of elements: %d\n", sum);
printf("Average: %.2f\n", (float)sum / size);
return 0;
}
Output:
Array elements: 10 20 30 40 50 Sum of elements: 150 Average: 30.00
Nested While Loops
1. Multiplication Table
#include <stdio.h>
int main() {
int i = 1;
printf("Multiplication Table:\n\n");
while (i <= 5) {
int j = 1;
while (j <= 5) {
printf("%4d", i * j);
j++;
}
printf("\n");
i++;
}
return 0;
}
Output:
Multiplication Table: 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
2. Number Pattern
#include <stdio.h>
int main() {
int rows = 5;
int i = 1;
printf("Number Pattern:\n\n");
while (i <= rows) {
int j = 1;
while (j <= i) {
printf("%d ", j);
j++;
}
printf("\n");
i++;
}
return 0;
}
Output:
Number Pattern: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Infinite Loops
1. Deliberate Infinite Loops
#include <stdio.h>
#include <unistd.h> // for sleep()
int main() {
int counter = 1;
// Server-style infinite loop
while (1) {
printf("Server running... iteration %d\n", counter++);
sleep(1); // Wait 1 second
// Add break condition
if (counter > 10) {
printf("Stopping server...\n");
break;
}
}
return 0;
}
2. Event Loop
#include <stdio.h>
#include <stdbool.h>
int main() {
bool running = true;
char command;
printf("Simple Command Processor\n");
printf("Commands: 'q' to quit, 'h' for help\n\n");
while (running) {
printf("> ");
scanf(" %c", &command);
if (command == 'q') {
running = false;
printf("Goodbye!\n");
} else if (command == 'h') {
printf("Available commands:\n");
printf(" q - quit\n");
printf(" h - help\n");
} else {
printf("Unknown command: %c\n", command);
}
}
return 0;
}
Do-While Loop
Syntax and Usage
do {
// code to be executed
} while (condition);
Key Difference: Do-While vs While
#include <stdio.h>
int main() {
printf("=== While Loop ===\n");
int x = 10;
while (x < 5) {
printf("This won't print\n");
x++;
}
printf("While loop skipped because condition is false\n\n");
printf("=== Do-While Loop ===\n");
int y = 10;
do {
printf("This prints at least once\n");
printf("y = %d\n", y);
y++;
} while (y < 5);
return 0;
}
Output:
=== While Loop === While loop skipped because condition is false === Do-While Loop === This prints at least once y = 10
Menu with Do-While
#include <stdio.h>
int main() {
int choice;
do {
printf("\n=== CALCULATOR MENU ===\n");
printf("1. Add\n");
printf("2. Subtract\n");
printf("3. Multiply\n");
printf("4. Divide\n");
printf("5. Exit\n");
printf("Choice: ");
scanf("%d", &choice);
if (choice >= 1 && choice <= 4) {
float a, b;
printf("Enter two numbers: ");
scanf("%f %f", &a, &b);
switch(choice) {
case 1:
printf("Result: %.2f\n", a + b);
break;
case 2:
printf("Result: %.2f\n", a - b);
break;
case 3:
printf("Result: %.2f\n", a * b);
break;
case 4:
if (b != 0)
printf("Result: %.2f\n", a / b);
else
printf("Error: Division by zero!\n");
break;
}
}
} while (choice != 5);
printf("Goodbye!\n");
return 0;
}
Loop Control Statements
1. Break Statement
#include <stdio.h>
int main() {
int i = 1;
printf("Break example - stop at 5:\n");
while (i <= 10) {
if (i == 5) {
printf("Breaking at i = %d\n", i);
break;
}
printf("i = %d\n", i);
i++;
}
return 0;
}
Output:
Break example - stop at 5: i = 1 i = 2 i = 3 i = 4 Breaking at i = 5
2. Continue Statement
#include <stdio.h>
int main() {
int i = 0;
printf("Continue example - skip even numbers:\n");
while (i < 10) {
i++;
if (i % 2 == 0) {
printf("Skipping %d\n", i);
continue;
}
printf("Processing odd number: %d\n", i);
}
return 0;
}
Output:
Continue example - skip even numbers: Processing odd number: 1 Skipping 2 Processing odd number: 3 Skipping 4 Processing odd number: 5 Skipping 6 Processing odd number: 7 Skipping 8 Processing odd number: 9 Skipping 10
3. Return from Loop
#include <stdio.h>
int findFirstEven(int arr[], int size) {
int i = 0;
while (i < size) {
if (arr[i] % 2 == 0) {
return arr[i]; // Return immediately when found
}
i++;
}
return -1; // Not found
}
int main() {
int numbers[] = {1, 3, 5, 6, 7, 9};
int size = sizeof(numbers) / sizeof(numbers[0]);
int result = findFirstEven(numbers, size);
if (result != -1) {
printf("First even number: %d\n", result);
} else {
printf("No even numbers found\n");
}
return 0;
}
Common While Loop Algorithms
1. Find Maximum in Array
#include <stdio.h>
int main() {
int numbers[] = {45, 23, 67, 12, 89, 34, 56};
int size = sizeof(numbers) / sizeof(numbers[0]);
int i = 1;
int max = numbers[0];
while (i < size) {
if (numbers[i] > max) {
max = numbers[i];
}
i++;
}
printf("Maximum value: %d\n", max);
return 0;
}
2. Linear Search
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50, 60, 70};
int size = sizeof(numbers) / sizeof(numbers[0]);
int target = 40;
int i = 0;
int found = 0;
while (i < size && !found) {
if (numbers[i] == target) {
found = 1;
printf("Found %d at index %d\n", target, i);
}
i++;
}
if (!found) {
printf("%d not found in array\n", target);
}
return 0;
}
3. Fibonacci Sequence
#include <stdio.h>
int main() {
int n = 10; // Number of terms
int first = 0, second = 1, next;
int count = 0;
printf("Fibonacci Sequence (%d terms):\n", n);
while (count < n) {
if (count <= 1) {
next = count;
} else {
next = first + second;
first = second;
second = next;
}
printf("%d ", next);
count++;
}
printf("\n");
return 0;
}
Output:
Fibonacci Sequence (10 terms): 0 1 1 2 3 5 8 13 21 34
Advanced While Loop Examples
1. Number Guessing Game
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int secret, guess;
int attempts = 0;
// Seed random number generator
srand(time(NULL));
secret = rand() % 100 + 1; // 1-100
printf("=== Number Guessing Game ===\n");
printf("Guess the number (1-100):\n");
while (1) {
printf("Enter your guess: ");
scanf("%d", &guess);
attempts++;
if (guess == secret) {
printf("Congratulations! You found it in %d attempts!\n", attempts);
break;
} else if (guess < secret) {
printf("Too low! Try again.\n");
} else {
printf("Too high! Try again.\n");
}
}
return 0;
}
2. Armstrong Number Checker
#include <stdio.h>
#include <math.h>
int main() {
int num, original, remainder, result = 0, n = 0;
printf("Enter an integer: ");
scanf("%d", &num);
original = num;
// Count digits
while (original != 0) {
original /= 10;
n++;
}
original = num;
// Calculate Armstrong sum
while (original != 0) {
remainder = original % 10;
result += pow(remainder, n);
original /= 10;
}
if (result == num) {
printf("%d is an Armstrong number.\n", num);
} else {
printf("%d is not an Armstrong number.\n", num);
}
return 0;
}
3. Prime Number Checker
#include <stdio.h>
int main() {
int num, i = 2;
int isPrime = 1;
printf("Enter a positive integer: ");
scanf("%d", &num);
if (num <= 1) {
isPrime = 0;
} else {
while (i <= num/2) {
if (num % i == 0) {
isPrime = 0;
break;
}
i++;
}
}
if (isPrime) {
printf("%d is a prime number.\n", num);
} else {
printf("%d is not a prime number.\n", num);
}
return 0;
}
4. Decimal to Binary Converter
#include <stdio.h>
int main() {
int decimal, binary[32], i = 0;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
int original = decimal;
// Convert to binary
while (decimal > 0) {
binary[i] = decimal % 2;
decimal = decimal / 2;
i++;
}
printf("Binary of %d is: ", original);
// Print in reverse order
while (i > 0) {
i--;
printf("%d", binary[i]);
}
printf("\n");
return 0;
}
Common Pitfalls and Solutions
1. Infinite Loop (Forgotten Update)
// WRONG - infinite loop
int i = 1;
while (i <= 5) {
printf("%d ", i);
// Missing i++ causes infinite loop
}
// CORRECT
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++; // Update counter
}
2. Off-by-One Errors
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
printf("=== Off-by-One Examples ===\n\n");
// WRONG - will access beyond array bounds
printf("WRONG - array index out of bounds:\n");
int i = 0;
while (i <= size) { // Should be i < size
printf("arr[%d] = %d\n", i, arr[i]);
i++;
if (i > size) break; // Prevent crash for demo
}
printf("\n");
// CORRECT
printf("CORRECT:\n");
i = 0;
while (i < size) {
printf("arr[%d] = %d\n", i, arr[i]);
i++;
}
return 0;
}
3. Semicolon After While
#include <stdio.h>
int main() {
int i = 1;
// WRONG - semicolon after while
while (i <= 5); { // Empty loop body!
printf("%d ", i);
i++;
}
// This would cause infinite loop
// CORRECT
i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
return 0;
}
4. Using Assignment Instead of Comparison
#include <stdio.h>
int main() {
int x = 5;
// WRONG - assignment (=) instead of comparison (==)
// while (x = 10) { // Always true, infinite loop
// printf("x = %d\n", x);
// x--;
// }
// CORRECT
while (x == 5) {
printf("x = %d\n", x);
x--;
}
return 0;
}
Performance Considerations
1. Loop Unrolling
#include <stdio.h>
int main() {
int array[1000];
int sum = 0;
int i = 0;
// Initialize array
while (i < 1000) {
array[i] = i;
i++;
}
printf("=== Loop Unrolling Example ===\n\n");
// Standard loop
i = 0;
sum = 0;
clock_t start = clock();
while (i < 1000) {
sum += array[i];
i++;
}
clock_t end = clock();
printf("Standard loop: %ld ticks\n", end - start);
// Unrolled loop (process 4 elements per iteration)
i = 0;
sum = 0;
start = clock();
while (i < 1000 - 3) {
sum += array[i] + array[i+1] + array[i+2] + array[i+3];
i += 4;
}
// Handle remaining elements
while (i < 1000) {
sum += array[i];
i++;
}
end = clock();
printf("Unrolled loop: %ld ticks\n", end - start);
return 0;
}
2. Minimize Function Calls
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
// BAD - strlen called each iteration
int i = 0;
while (i < strlen(str)) { // strlen called repeatedly
putchar(str[i]);
i++;
}
printf("\n");
// GOOD - strlen called once
int len = strlen(str);
i = 0;
while (i < len) {
putchar(str[i]);
i++;
}
printf("\n");
return 0;
}
Best Practices Summary
Do's and Don'ts
// DO: Use meaningful loop variable names
int studentIndex = 0;
while (studentIndex < totalStudents) {
processStudent(students[studentIndex]);
studentIndex++;
}
// DON'T: Use single-letter variables in complex loops
int i = 0;
while (i < 1000) {
// Hard to understand what i represents
}
// DO: Keep loop body focused and readable
while (condition) {
doOneThing();
doAnotherThing();
updateCounter();
}
// DON'T: Have massive loop bodies
while (condition) {
// 100 lines of code - hard to debug
}
// DO: Use break and continue sparingly
while (processing) {
if (error) {
break; // Clear exit condition
}
processData();
}
// DON'T: Overuse break and continue
while (condition) {
if (x) break;
if (y) continue;
if (z) break;
// Hard to follow flow
}
Comparison with Other Loops
| Feature | While Loop | Do-While Loop | For Loop |
|---|---|---|---|
| Condition check | Beginning | End | Beginning |
| Minimum iterations | 0 | 1 | 0 |
| Best for | Unknown iterations | Menu-driven | Known iterations |
| Syntax | while(cond) {} | do {} while(cond); | for(init;cond;inc){} |
| Common use | Reading files | Input validation | Array traversal |
Conclusion
The while loop is a versatile and fundamental control structure in C:
Key Takeaways
- Pre-test loop - checks condition before execution
- Zero or more iterations - may not execute at all
- Must update condition - to avoid infinite loops
- Flexible - works well with unknown iteration counts
- Do-while variant - guarantees at least one execution
When to Use While Loops
- Reading files until EOF
- Processing user input
- Menu-driven programs
- Game loops
- Waiting for events
- Algorithms with unknown iteration counts
Common Mistakes to Avoid
- Forgetting to update loop variable
- Using assignment instead of comparison
- Semicolon after while statement
- Off-by-one errors
- Infinite loops
Mastering while loops is essential for writing efficient and correct C programs. They provide the foundation for many algorithms and are indispensable for any C programmer.