C Programming: Loops
What is a Loop in C?
A loop is a control structure that allows you to execute a block of code repeatedly based on a condition.
Types of Loops in C
1. for Loop:
Used when the number of iterations is known.
Syntax:
for(initialization; condition; increment/decrement) {
// Code to be repeated
Example:
for(int i = 1; i <= 5; i++) {
printf("%d\n", i);
2. while Loop:
Used when the number of iterations is not known.
Syntax:
while(condition) {
// Code to be repeated
Example:
int i = 1;
while(i <= 5) {
printf("%d\n", i);
i++;
3. do...while Loop:
Runs at least once, even if the condition is false.
Page 1
C Programming: Loops
Syntax:
do {
// Code to be repeated
} while(condition);
Example:
int i = 1;
do {
printf("%d\n", i);
i++;
} while(i <= 5);
Key Concepts:
- Initialization - setting a starting point (e.g., i = 0)
- Condition - loop continues as long as true (e.g., i < 5)
- Increment/Decrement - modifies loop control variable (e.g., i++)
Loop Control Statements:
break; - Exits the loop immediately.
continue; - Skips the current iteration.
Example with break:
for(int i = 1; i <= 10; i++) {
if(i == 5) break;
printf("%d\n", i);
Example with continue:
for(int i = 1; i <= 5; i++) {
if(i == 3) continue;
printf("%d\n", i); // Skips 3
Page 2
C Programming: Loops
Real Examples:
Sum of numbers from 1 to N:
int sum = 0, i = 1;
while(i <= 10) {
sum += i;
i++;
printf("Sum = %d", sum);
Factorial of a number:
int n = 5, fact = 1;
for(int i = 1; i <= n; i++) {
fact *= i;
printf("Factorial = %d", fact);
Summary Table:
Loop Type | Condition Checked | Minimum Runs | Best For
-------------------------------------------------------------
for | Before each loop | 0 | Known iterations
while | Before each loop | 0 | Unknown iterations
do...while | After each loop | At least 1 | At least once execution
Page 3