For loops are ideal when the number of iterations is known in advance. Below are three practcial implementations.
Summing Sequential Integers
Given a positive integer n, compute and display the cumulative sums: 1, 1+2, 1+2+3, ..., up to the n-th term.
int main() { int n, total = 0; printf("Enter a number: "); scanf("%d", &n);
for (int term = 1; term <= n; term++) {
total += term;
printf("%d ", total);
}
return 0;
}
</div>#### Alternating Factorial Series
Calculate the sum of the series: 1 - 3! + 5! - 7! + ... ± (2n-1)!, where the sign alternates with each term.
<div>```
#include <stdio.h>
int main() {
int n;
float seriesSum = 0.0;
int sign = 1;
printf("Enter n: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
float factorial = 1.0;
int limit = 2 * i - 1;
for (int j = 1; j <= limit; j++) {
factorial *= j;
}
seriesSum += sign * factorial;
sign = -sign;
}
printf("Sum: %.0f\n", seriesSum);
return 0;
}
While loops are suited for scenarios where iteration continues until a condition is met.
Tracking Student Scores
Read a sequence of student scores untill a negative value is entered. Output the highest and lowest valid scores.
int main() { float score, maxScore, minScore;
printf("Enter scores (negative to stop):\n");
scanf("%f", &score);
if (score < 0) {
printf("No valid scores entered.\n");
return 0;
}
maxScore = minScore = score;
while (score >= 0) {
if (score > maxScore) maxScore = score;
if (score < minScore) minScore = score;
scanf("%f", &score);
}
printf("Highest: %.2f\n", maxScore);
printf("Lowest: %.2f\n", minScore);
return 0;
}
</div>#### Finding Narcissistic Numbers
A narcissistic number is a 3-digit number equal to the sum of the cubes of its digits (e.g., 153 = 1³ + 5³ + 3³).
<div>```
#include <stdio.h>
int main() {
for (int num = 100; num <= 999; num++) {
int hundreds = num / 100;
int tens = (num / 10) % 10;
int units = num % 10;
if (hundreds*hundreds*hundreds + tens*tens*tens + units*units*units == num) {
printf("%d\n", num);
}
}
return 0;
}
Do-while loops guarantee at least one execution, useful when the condition depends on prior computation.
Harmonic Series Threshold
Find the smallest integer n such that the harmonic sum 1 + 1/2 + 1/3 + ... + 1/n exceeds a given threshold value.
int main() { float target, total = 0.0; int count = 0;
printf("Enter threshold value: ");
scanf("%f", &target);
do {
count++;
total += 1.0f / count;
} while (total < target);
printf("Minimum n: %d\n", count);
return 0;
}
</div>### Combining while and for Loops
Combine loop types to enforce input validation within a structured iteration.
#### Converting Four Digits to Integer
Read exactly four valid decimal digits (0–9), ignoring invalid input, and construct a 4-digit integer.
<div>```
#include <stdio.h>
int main() {
int result = 0;
char digit;
for (int pos = 0; pos < 4; pos++) {
while (1) {
digit = getchar();
if (digit >= '0' && digit <= '9') break;
}
int value = digit - '0';
if (pos == 0) result += value * 1000;
else if (pos == 1) result += value * 100;
else if (pos == 2) result += value * 10;
else result += value;
}
printf("Result: %d\n", result);
return 0;
}
Nested loops enable multi-dimensional iteration, useful for combinatorial problems.
Classic Horse and Load Problem
100 horses carry 100 loads. Large horses carry 3 loads each, medium carry 2, and two small horses carry 1. Find all valid combinations.
int main() { int large, medium, small, count = 0;
printf("Valid combinations:\n");
for (large = 1; large <= 33; large++) {
for (medium = 1; medium <= 50; medium++) {
small = 100 - large - medium;
if (small < 0) continue;
if (small % 2 == 0 && 3*large + 2*medium + small/2.0 == 100) {
printf("Large: %3d, Medium: %3d, Small: %3d\n", large, medium, small);
count++;
}
}
}
printf("Total combinations: %d\n", count);
return 0;
}
</div>#### Arithmetic Sequence with Contsraints
Find a 6-term arithmetic sequence where the sum of the first four terms is 26 and their product is 880.
<div>```
#include <stdio.h>
int main() {
int first, diff, sum = 0;
for (first = 1; first <= 20; first++) {
for (diff = 1; diff <= 10; diff++) {
int term1 = first;
int term2 = first + diff;
int term3 = first + 2*diff;
int term4 = first + 3*diff;
if (term1 + term2 + term3 + term4 != 26) continue;
if (term1 * term2 * term3 * term4 != 880) continue;
printf("Sequence: ");
for (int i = 0; i < 6; i++) {
int current = first + i * diff;
printf("%d ", current);
sum += current;
}
printf("\n");
break;
}
}
printf("Sum of first six terms: %d\n", sum);
return 0;
}
30 students spent 50 yuan total. University students pay 3 yuan, high school students 2 yuan, and elementary students 1 yuan. Find all combinations where each group has at least one member.
int main() { int uni, high, elem, solutions = 0;
for (uni = 1; uni <= 16; uni++) {
for (high = 1; high <= 24; high++) {
elem = 30 - uni - high;
if (elem <= 0) continue;
if (3*uni + 2*high + elem == 50) {
printf("Uni: %3d, High: %3d, Elem: %3d\n", uni, high, elem);
solutions++;
}
}
}
printf("Total valid solutions: %d\n", solutions);
return 0;
}
</div></div>