Loops in C
Loops in C
Introduction
In programming, repeating a task multiple times is very common. Writing the same code again and again is not efficient.
This is where loops come into play.
👉 Loops allow us to execute a block of code multiple times based on a condition.
What is a Loop?
A loop is a control structure that:
- Executes a block of code repeatedly
- Stops when a condition becomes false
👉 In simple terms:
Loop = Repeat until condition fails
Why Do We Use Loops?
- ✔ Reduce code repetition
- ✔ Save time and effort
- ✔ Make programs efficient
- ✔ Handle large data easily
Types of Loops in C
-
forloop -
whileloop -
do-whileloop
1. for Loop
Used when the number of iterations is known.
Syntax
for (initialization; condition; increment/decrement) {
// code
}
How It Works
- Initialization executes once
- Condition is checked
- Code executes if condition is true
- Increment/decrement happens
- Repeat
Example
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output
1
2
3
4
5
Use Case
👉 Printing numbers, patterns, fixed iterations
2. while Loop
Used when the number of iterations is not known.
Syntax
while (condition) {
// code
}
How It Works
- Condition is checked first
- If true → code runs
- If false → loop stops
Example
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
return 0;
}
Output
1
2
3
4
5
Use Case
👉 User input loops, unknown iterations
3. do-while Loop
Executes code at least once.
Syntax
do {
// code
} while (condition);
How It Works
- Code executes first
- Then condition is checked
Example
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output
1
2
3
4
5
Use Case
👉 Menu-driven programs, user interaction
Nested Loops (Important)
A loop inside another loop is called a nested loop.
Example
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 3; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output
* * *
* * *
* * *
⚠️ Infinite Loop
A loop that never ends.
Example
while(1) {
printf("Infinite Loop");
}
Comparison Table
| Loop Type | Condition Check | Use Case |
|---|---|---|
| for | Before execution | Known iterations |
| while | Before execution | Unknown iterations |
| do-while | After execution | Execute at least once |
Common Mistakes
- ❌ Forgetting increment/decrement
- ❌ Writing wrong condition
- ❌ Creating infinite loops
- ❌ Using wrong loop type
Pro Tips
-
✔ Use
forfor known loops -
✔ Use
whilefor conditions -
✔ Use
do-whilefor user interaction - ✔ Avoid deep nesting
- ✔ Always check loop condition carefully
Conclusion
Loops are a fundamental concept in C programming. They help reduce code repetition and improve efficiency.
Mastering loops will help you solve complex problems easily.
Comments
Post a Comment