Loops
Duration: 50 min
Loops allow you to execute a block of code repeatedly. C provides three types of loops: for, while, and do-while. You can also use break and continue to control loop execution.
for Loop
#include <stdio.h>
int main() {
// Print numbers 1 to 5
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
printf("\n");
// Syntax: for (initialization; condition; increment)
// initialization: runs once before loop
// condition: checked before each iteration
// increment: runs after each iteration
return 0;
}while Loop
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
printf("\n");
// Useful when you don't know how many iterations needed
int sum = 0, num = 0;
while (num < 10) {
sum += num;
num++;
}
printf("Sum: %d\n", sum);
return 0;
}do-while Loop
#include <stdio.h>
int main() {
int i = 1;
// Executes at least once, even if condition is false
do {
printf("%d ", i);
i++;
} while (i <= 5);
printf("\n");
// Useful for menu-driven programs
int choice;
do {
printf("Enter 1 to continue, 0 to exit: ");
scanf("%d", &choice);
} while (choice != 0);
return 0;
}break Statement
#include <stdio.h>
int main() {
// Exit loop when condition is met
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop
}
printf("%d ", i);
}
printf("\n"); // Output: 1 2 3 4
return 0;
}continue Statement
#include <stdio.h>
int main() {
// Skip current iteration and go to next
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip this iteration
}
printf("%d ", i);
}
printf("\n"); // Output: 1 2 4 5
return 0;
}Nested Loops
#include <stdio.h>
int main() {
// Print multiplication table
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", i * j);
}
printf("\n");
}
// Output:
// 1 2 3
// 2 4 6
// 3 6 9
return 0;
}Practical Examples
#include <stdio.h>
int main() {
// Calculate factorial
int n = 5;
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
printf("Factorial of %d: %d\n", n, factorial);
// Find sum of digits
int num = 12345;
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
printf("Sum of digits: %d\n", sum);
return 0;
}Quiz 1: for Loop
❓ How many times will this loop execute? for (int i = 0; i < 5; i++)
Quiz 2: while Loop
❓ What is the key difference between while and do-while?
Quiz 3: break Statement
❓ What will print? for (int i = 1; i <= 5; i++) { if (i == 3) break; printf("%d ", i); }
Quiz 4: continue Statement
❓ What will print? for (int i = 1; i <= 5; i++) { if (i == 3) continue; printf("%d ", i); }
Quiz 5: Nested Loops
❓ How many times will the inner loop execute in nested loops: for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++)?