C For Loop Real-Life Examples
Practical Applications of For Loops
For loops are used extensively in real-world programming for tasks that require controlled repetition. They are particularly useful when the number of iterations is known in advance or can be determined programmatically.
This section explores practical examples of how for loops are used in real programming scenarios.
Array Processing
For loops are ideal for processing arrays, as they can easily iterate through each element using an index variable.
#include <stdio.h>
int main(void) {
int numbers[] = {12, 45, 23, 67, 34, 89, 56};
int size = (int)(sizeof(numbers) / sizeof(numbers[0]));
int max = numbers[0];
for (int i = 1; i < size; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
printf("Maximum value: %d\n", max);
int sum = 0;
for (int i = 0; i < size; i++) {
sum += numbers[i];
}
double average = (double)sum / size;
printf("Average: %.2f\n", average);
printf("Reversed array: ");
for (int i = size - 1; i >= 0; i--) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Maximum value: 89 Average: 46.57 Reversed array: 56 89 34 67 23 45 12
String Manipulation
For loops are commonly used for string processing tasks like counting characters, reversing strings, or converting cases.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void) {
char text[] = "Hello, World!";
int length = (int)strlen(text);
int vowelCount = 0;
for (int i = 0; i < length; i++) {
char c = (char)tolower((unsigned char)text[i]);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
printf("Vowel count: %d\n", vowelCount);
printf("Uppercase: ");
for (int i = 0; i < length; i++) {
printf("%c", toupper((unsigned char)text[i]));
}
printf("\nReversed: ");
for (int i = length - 1; i >= 0; i--) {
printf("%c", text[i]);
}
// optional: put a trailing newline
// printf("\n");
return 0;
}
Vowel count: 3 Uppercase: HELLO, WORLD! Reversed: !dlroW ,olleH
Mathematical Calculations
For loops are essential for many mathematical computations, including series summation, prime number checking, and factorial calculations.
#include <stdio.h>
#include <math.h>
int main(void) {
printf("Fibonacci series (first 10 terms): ");
int n1 = 0, n2 = 1, n3;
printf("%d %d ", n1, n2);
for (int i = 2; i < 10; i++) {
n3 = n1 + n2;
printf("%d ", n3);
n1 = n2;
n2 = n3;
}
int num = 29;
int isPrime = 1;
int limit = (int)sqrt((double)num);
for (int i = 2; i <= limit; i++) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
printf("\n%d is %s prime number\n", num, isPrime ? "a" : "not a");
int n = 5;
float seriesSum = 0.0f;
for (int i = 1; i <= n; i++) {
seriesSum += 1.0f / (float)i;
}
printf("Sum of harmonic series (n=%d): %.4f", n, seriesSum);
return 0;
}
Fibonacci series (first 10 terms): 0 1 1 2 3 5 8 13 21 34 29 is a prime number Sum of harmonic series (n=5): 2.2833
File Processing
For loops can be used in file processing to read or write a specific number of records or to process data in chunks.
#include <stdio.h>
int main(void) {
FILE *file;
const char *filename = "data.txt";
file = fopen(filename, "w");
if (file == NULL) {
printf("Error creating file!\n");
return 1;
}
for (int i = 1; i <= 10; i++) {
fprintf(file, "%d\n", i * i);
}
fclose(file);
file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
int value, sum = 0;
printf("Values from file: ");
for (int i = 0; i < 10; i++) {
if (fscanf(file, "%d", &value) != 1) {
printf("\nUnexpected read error or EOF\n");
fclose(file);
return 1;
}
printf("%d ", value);
sum += value;
}
fclose(file);
printf("\nSum of values: %d", sum);
return 0;
}
Values from file: 1 4 9 16 25 36 49 64 81 100 Sum of values: 385
Game Development
For loops are used in game development for various tasks like rendering multiple objects, processing game entities, and implementing game logic.
#include <stdio.h>
int main(void) {
int numEnemies = 5;
int enemyHealth[] = {100, 80, 120, 90, 110};
int playerDamage = 30;
printf("Combat simulation:\n");
printf("Player damage per attack: %d\n\n", playerDamage);
for (int enemy = 0; enemy < numEnemies; enemy++) {
printf("Fighting enemy %d (Health: %d)\n", enemy + 1, enemyHealth[enemy]);
int attacksNeeded = 0;
int currentHealth = enemyHealth[enemy];
for (; currentHealth > 0; attacksNeeded++) {
currentHealth -= playerDamage;
if (currentHealth < 0) currentHealth = 0;
printf(" Attack %d: Enemy health now %d\n", attacksNeeded + 1, currentHealth);
}
printf("Enemy %d defeated in %d attacks\n\n", enemy + 1, attacksNeeded);
}
return 0;
}
Combat simulation: Player damage per attack: 30 Fighting enemy 1 (Health: 100) Attack 1: Enemy health now 70 Attack 2: Enemy health now 40 Attack 3: Enemy health now 10 Attack 4: Enemy health now 0 Enemy 1 defeated in 4 attacks Fighting enemy 2 (Health: 80) Attack 1: Enemy health now 50 Attack 2: Enemy health now 20 Attack 3: Enemy health now 0 Enemy 2 defeated in 3 attacks Fighting enemy 3 (Health: 120) Attack 1: Enemy health now 90 Attack 2: Enemy health now 60 Attack 3: Enemy health now 30 Attack 4: Enemy health now 0 Enemy 3 defeated in 4 attacks Fighting enemy 4 (Health: 90) Attack 1: Enemy health now 60 Attack 2: Enemy health now 30 Attack 3: Enemy health now 0 Enemy 4 defeated in 3 attacks Fighting enemy 5 (Health: 110) Attack 1: Enemy health now 80 Attack 2: Enemy health now 50 Attack 3: Enemy health now 20 Attack 4: Enemy health now 0 Enemy 5 defeated in 4 attacks
Data Analysis
For loops are fundamental in data analysis tasks like statistical calculations, data filtering, and transformation.
#include <stdio.h>
int main(void) {
int grades[] = {85, 92, 78, 90, 65, 88, 72, 95, 81, 87};
int numStudents = (int)(sizeof(grades) / sizeof(grades[0]));
int sum = 0, max = grades[0], min = grades[0];
int passCount = 0, failCount = 0;
for (int i = 0; i < numStudents; i++) {
sum += grades[i];
if (grades[i] > max) max = grades[i];
if (grades[i] < min) min = grades[i];
if (grades[i] >= 60) {
passCount++;
} else {
failCount++;
}
}
double average = (double)sum / numStudents;
printf("Grade Analysis:\n");
printf("Number of students: %d\n", numStudents);
printf("Average grade: %.2f\n", average);
printf("Highest grade: %d\n", max);
printf("Lowest grade: %d\n", min);
printf("Passing students (>=60): %d\n", passCount);
printf("Failing students: %d\n", failCount);
printf("\nGrade Distribution:\n");
const char *ranges[] = {"90-100", "80-89", "70-79", "60-69", "Below 60"};
int counts[] = {0, 0, 0, 0, 0};
for (int i = 0; i < numStudents; i++) {
if (grades[i] >= 90) counts[0]++;
else if (grades[i] >= 80) counts[1]++;
else if (grades[i] >= 70) counts[2]++;
else if (grades[i] >= 60) counts[3]++;
else counts[4]++;
}
for (int i = 0; i < 5; i++) {
printf("%s: %d students\n", ranges[i], counts[i]);
}
return 0;
}
Grade Analysis: Number of students: 10 Average grade: 83.30 Highest grade: 95 Lowest grade: 65 Passing students (>=60): 10 Failing students: 0 Grade Distribution: 90-100: 3 students 80-89: 4 students 70-79: 2 students 60-69: 1 students Below 60: 0 students
Best Practices in Real-World Code
1. Use meaningful variable names for loop counters when appropriate
2. Prefer local loop variables when possible to avoid side effects
3. Consider using functions for complex loop bodies to improve readability
4. Be mindful of performance with large iteration counts
5. Use the most appropriate loop type for your specific use case
6. Always include boundary checks to prevent buffer overflows
7. Cache repeated computations used in loop conditions (e.g., store strlen(text) in a variable)
8. When using