What is a Loop in C? (for, while, do-while Explained Simply)
When learning C programming, one important concept you will see again and again is loops.
But what exactly is a loop?
Let’s understand it in a very simple way.
What is a Loop?
A loop is used to repeat a block of code multiple times.
Instead of writing the same code again and again, you can use a loop.
👉 Example:
If you want to print numbers from 1 to 5, you don’t need to write 5 print statements. A loop can do it for you.
Types of Loops in C
There are three main types of loops in C:
- for loop
- while loop
- do-while loop
1. for Loop
The for loop is used when you know how many times you want to repeat something.
Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}👉 This will print numbers from 1 to 5.
2. while Loop
The while loop is used when you want to repeat something until a condition is true.
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 runs at least one time, even if the condition is false.
Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while(i <= 5);
return 0;
}Key Difference
- for → when you know the number of repetitions
- while → when condition matters
- do-while → runs at least once no matter what
Final Thoughts
Loops make your code:
- Short
- Clean
- Efficient
If you understand loops well, you will become much better at programming.
JazakAllah for reading!
Comments
Post a Comment