Loops Introduction
In programming, loops are used to repeat a block of code multiple times. This is helpful when you want to perform the same task again and again without writing the same code repeatedly.
Types of Loops
- for loop – when you know how many times to run
- while loop – when you don't know how many times, but you want to repeat while a condition is true
- do-while loop – similar to while loop, but it runs at least once
For Loop
The for loop is one of the most commonly used loops in C programming. It's perfect when you know exactly how many times you want to repeat a block of code. Think of it like setting a timer - you decide how many times something should happen, and the loop takes care of the counting for you!
Syntax
for (initialization; condition; increment/decrement) {
// Code to be executed
}
The for loop has three parts separated by semicolons:
- Initialization: Sets up a counter variable (executed once at the beginning)
- Condition: Checked before each iteration (loop continues while true)
- Increment/Decrement: Updates the counter after each iteration
How It Works
Here's a simple example that prints numbers from 1 to 5:
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
return 0;
}
Output: 1 2 3 4 5
Let's break down what happens:
int i = 1- Initialize counterito 1i <= 5- Check ifiis less than or equal to 5- If true, execute
printf("%d ", i) i++- Incrementiby 1- Repeat steps 2-4 until condition becomes false
Common Patterns
Counting Up
// Print numbers 0 to 9
for (int i = 0; i < 10; i++) {
printf("%d ", i);
}
Counting Down
// Print numbers 10 to 1
for (int i = 10; i >= 1; i--) {
printf("%d ", i);
}
Custom Increments
// Print even numbers from 0 to 10
for (int i = 0; i <= 10; i += 2) {
printf("%d ", i);
}
Multiplication Table
Printing Multiplication Tables is a very good real world use case to understand the importance of loops. Following code prints the 5 table.
#include <stdio.h>
int main() {
int num = 5;
printf("Multiplication table of %d:\n\n", num);
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0;
}
This print the following
Multiplication table of 5:
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Key Points to Remember
- The loop variable (
iin our examples) is often called a counter or iterator - You can use any variable name, but
i,j,kare common conventions - The initialization happens only once, but condition and increment happen every iteration
- If the condition is false from the start, the loop body won't execute at all
- Be careful with the condition to avoid infinite loops!