Looping statements are used to execute a block of code repeatedly, either for a specific number of times or until a condition is met.
Thank you for reading this post, don't forget to subscribe!- A loop continues to execute as long as its condition remains true.
- Loops help in situations where repetitive tasks are required.
Types of Looping Statement in C:
- for loop
- while loop
- do-while loop
1.) for loop
The for loop is used when you know beforehand how many times you want to execute a statement or a block of statements.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}Example:
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("Number: %d\n", i);
}
return 0;
}2.) while loop
The while loop is used to execute a block of code as long as the specified condition is true. It checks the condition before executing the loop.
Syntax:
while (condition) {
// Code to execute
}Example:
#include <stdio.h>
int main() {
int count = 1;
while (count <= 5) {
printf("Count: %d\n", count);
count++;
}
return 0;
}3.) do-while Loop:
The do-while loop is similar to the while loop, but it executes the loop body first and then checks the condition. So the loop executes at least once.
Syntax:
do {
// Code to execute
} while (condition);Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("Value: %d\n", i);
i++;
} while (i <= 5);
return 0;
}