Loops
intermediatePart of Program Flow in C
Theory
Loops allow you to execute a block of code repeatedly. C provides three loop constructs: for, while, and do-while. Choosing the right loop depends on your use case.
for loop is best when you know the number of iterations in advance:
for (initialization; condition; increment) {
// body
}The initialization runs once at the start. The condition is checked before each iteration. The increment runs after each iteration. All three parts are optional.
for (int i = 0; i < 5; i++) {
printf("%d ", i); // 0 1 2 3 4
}while loop runs as long as a condition is true. It checks the condition before executing the body — if the condition is initially false, the body never runs.
int count = 0;
while (count < 5) {
printf("%d ", count);
count++;
}do-while loop is similar to while but guarantees at least one execution — the condition is checked after the body runs.
int x = 0;
do {
printf("%d ", x);
x++;
} while (x < 5);Loop control statements:
break— exits the current loop immediatelycontinue— skips the rest of the current iteration and goes to the nextgoto— jumps to a labeled statement (use sparingly)
Infinite loops run forever. Common patterns: while(1), for(;;). Use them intentionally (e.g., server loops) and ensure there's a break condition.
Nested loops place one loop inside another. The inner loop runs completely for each iteration of the outer loop. Useful for multi-dimensional data, patterns, and tables.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("(%d,%d) ", i, j);
}
}Common loop use cases:
- Iterating through arrays
- Input validation (repeat until valid)
- Generating patterns and tables
- Counting and accumulating sums
Practical Examples
Exercises
Sum of Natural Numbers
Write a C program that uses a for loop to calculate the sum of natural numbers from 1 to n, where n is entered by the user. Also calculate the average.
Expected Output:
Enter a number: 10\nSum: 55\nAverage: 5.50Number Pattern Pyramid
Use nested for loops to print a number pyramid. Each row i contains numbers from 1 to i. The pyramid should have 5 rows.
Starter Code:
#include <stdio.h>\n\nint main() {\n // Nested loops for pyramid\n return 0;\n}Expected Output:
1\n12\n123\n1234\n12345Prime Number Checker
Write a program that takes a number from the user and determines if it is prime. Use a for loop with a break statement. A prime number is divisible only by 1 and itself.
Expected Output:
Enter a number: 17\n17 is a prime number.Mini Quiz
Mini Quiz
Mini Project
Mini Project: Multiplication Table Generator
Create a C program that generates a formatted multiplication table. Use nested loops to print rows and columns, and loop control statements to customize the output.
Requirements:
Bonus Challenge
Highlight prime numbers in the table by printing them with a marker (e.g., 5*).