🔁 Loops in C Programming
for, while & do-while Loops Explained
Learn How to Repeat Tasks Automatically in C 🚀
🚀 Introduction
Imagine you want a program to print Hello World 100 times.
Would you write the same printf() statement 100 times?
Of course not!
This is where loops become useful. A loop allows a program to execute the same block of code repeatedly while a condition is satisfied.
💡 In simple words:
Loop = Repeat a task automatically.
🔄 Three Main Types of Loops in C
🔢 for
Best when the number of repetitions is known.
🔄 while
Best when repetition depends on a condition.
▶️ do-while
Runs the code at least once.
1️⃣ for Loop
The for loop is commonly used when you know how many times you want to repeat an operation.
Syntax:
for(initialization; condition; update)
{
// statements
}
Example:
#include <stdio.h>
int main()
{
int i;
for(i = 1; i <= 5; i++)
{
printf("%d\n", i);
}
return 0;
}
Output:
2
3
4
5
🔍 How the for Loop Works
| Part | Purpose |
|---|---|
| i = 1 | Initial value |
| i <= 5 | Condition |
| i++ | Increase value by 1 |
The loop continues until the condition becomes false.
2️⃣ while Loop
A while loop checks the condition before executing the loop body.
Syntax:
while(condition)
{
// statements
}
Example:
#include <stdio.h>
int main()
{
int i = 1;
while(i <= 5)
{
printf("%d\n", i);
i++;
}
return 0;
}
3️⃣ do-while Loop
The do-while loop is different because the code executes first and the condition is checked afterward.
Syntax:
do
{
// statements
}
while(condition);
Example:
#include <stdio.h>
int main()
{
int i = 1;
do
{
printf("%d\n", i);
i++;
}
while(i <= 5);
return 0;
}
⚖️ for vs while vs do-while
| Loop | Condition Checked | Minimum Executions |
|---|---|---|
| for | Before | 0 |
| while | Before | 0 |
| do-while | After | 1 |
🌍 Real-Life Examples of Loops
- 🔢 Counting numbers from 1 to 100
- 📋 Displaying all student records
- 🛒 Processing products in an online store
- 🎮 Repeating a game until the player exits
- 🏦 Processing multiple banking transactions
🛑 break and continue
break
The break statement immediately stops a loop.
for(i = 1; i <= 10; i++)
{
if(i == 5)
break;
printf("%d\n", i);
}
continue
The continue statement skips the current iteration and moves to the next iteration.
🚀 Practice Programs
- Print numbers from 1 to 100
- Print even numbers from 1 to 50
- Calculate the sum of numbers from 1 to 100
- Print the multiplication table of a number
- Find the factorial of a number
- Reverse a number using a loop
🎯 Conclusion
Loops are one of the most important concepts in programming. They allow us to repeat tasks efficiently without writing the same code again and again.
Once you understand loops, you can solve many programming problems much more easily.
No comments:
Post a Comment