C While Loop Real-Life Examples
Practical Applications of While Loops
While loops are used extensively in real-world programming for tasks that require repetition until a certain condition is met. They are particularly useful when the number of iterations is not known in advance.
This section explores practical examples of how while loops are used in real programming scenarios.
User Input Validation
While loops are ideal for validating user input, ensuring that the program continues to prompt the user until valid input is provided.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char buf[64];
long age;
char *end;
while (1) {
printf("Enter your age: ");
if (!fgets(buf, sizeof(buf), stdin)) {
printf("Input error.\n");
return 1;
}
age = strtol(buf, &end, 10);
if (end == buf || (*end != '\n' && *end != '\0')) {
printf("Invalid input! Please enter digits only.\n");
continue;
}
if (age <= 0 || age > 120) {
printf("Invalid age! Please enter a value between 1 and 120.\n");
continue;
}
break;
}
printf("Your age is: %ld\n", age);
return 0;
}
Enter your age: -5 Invalid age! Please enter a value between 1 and 120. Enter your age: 150 Invalid age! Please enter a value between 1 and 120. Enter your age: 25 Your age is: 25
Menu-Driven Programs
While loops are commonly used in menu-driven programs where the user can repeatedly choose options until they decide to exit.
This example uses a do-while loop (a variant of while) to ensure the menu shows at least once.
#include <stdio.h>
int main(void) {
int choice;
do {
// Display menu
printf("\n=== MENU ===\n");
printf("1. Option One\n");
printf("2. Option Two\n");
printf("3. Option Three\n");
printf("4. Exit\n");
printf("Enter your choice: ");
if (scanf("%d", &choice) != 1) {
// Clear invalid input
int c; while ((c = getchar()) != '\n' && c != EOF) {}
choice = 0;
}
// Process choice
switch (choice) {
case 1:
printf("You selected Option One.\n");
break;
case 2:
printf("You selected Option Two.\n");
break;
case 3:
printf("You selected Option Three.\n");
break;
case 4:
printf("Exiting program. Goodbye!\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 4);
return 0;
}
=== MENU === 1. Option One 2. Option Two 3. Option Three 4. Exit Enter your choice: 2 You selected Option Two. === MENU === 1. Option One 2. Option Two 3. Option Three 4. Exit Enter your choice: 5 Invalid choice! Please try again. === MENU === 1. Option One 2. Option Two 3. Option Three 4. Exit Enter your choice: 4 Exiting program. Goodbye!
File Processing
While loops are essential for reading files where you don't know the exact number of records in advance.
#include <stdio.h>
int main(void) {
FILE *file;
const char *filename = "data.txt";
char buffer[100];
// Open file for reading
file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// Read file line by line
printf("File contents:\n");
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
// Close file
fclose(file);
return 0;
}
File contents: Line 1: This is sample data Line 2: Another line of text Line 3: End of file
Game Development
While loops form the core of game loops, which continuously update game state and render graphics until the game ends.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool gameRunning = true;
int playerHealth = 100;
int score = 0;
printf("Game started!\n");
// Main game loop
while (gameRunning) {
// Simulate game events
playerHealth -= 10;
score += 5;
printf("Health: %d, Score: %d\n", playerHealth, score);
// Check game over condition
if (playerHealth <= 0) {
printf("Game Over! Final score: %d\n", score);
gameRunning = false;
}
// Simulate frame delay (placeholder)
for (volatile int i = 0; i < 100000000; i++) {}
}
return 0;
}
Game started! Health: 90, Score: 5 Health: 80, Score: 10 Health: 70, Score: 15 Health: 60, Score: 20 Health: 50, Score: 25 Health: 40, Score: 30 Health: 30, Score: 35 Health: 20, Score: 40 Health: 10, Score: 45 Health: 0, Score: 50 Game Over! Final score: 50
Data Processing
While loops are used for processing data streams or collections where the termination condition depends on the data itself.
#include <stdio.h>
int main(void) {
int numbers[] = {5, 12, 8, 19, 3, 15, 7, 0}; // 0 marks the end
int i = 0;
int sum = 0;
int count = 0;
// Process numbers until we reach 0
while (numbers[i] != 0) {
sum += numbers[i];
count++;
i++;
}
printf("Processed %d numbers.\n", count);
printf("Sum: %d, Average: %.2f\n", sum, (float)sum / count);
return 0;
}
Processed 7 numbers. Sum: 69, Average: 9.86
Best Practices in Real-World Code
1. Always validate input to prevent infinite loops
2. Use meaningful variable names for loop conditions
3. Consider using for loops when the number of iterations is known
4. Use break and continue judiciously to improve code clarity
5. Ensure loop conditions will eventually become false
6. Add comments to explain the purpose of complex loops
7. Test edge cases to ensure loops terminate correctly