What is Loopsin C Programming
language?
In C programming, loops are control structures that allow you
to execute a block of code repeatedly based on a condition.
They are used to perform repetitive tasks efficiently without
writing the same code multiple times.
Or to execute a piece of code again and again.
3.
Types of loopsin C programming language?
In C programming, there are three main types of loops:
1. ‘for’ Loop
2. ‘while’ Loop
3. ‘do-while’ Loop
4.
1. ‘for’ Loop● Used when the number of
iterations is known beforehand.
#include <stdio.h>
int main() {
for(int i = 0; i < 5; i++) {
printf("i = %dn", i);
}
return 0; }
Explanation: This loop prints
values from 0 to 4.
Syntax
5.
2. ‘while’ Loop● Used when the number of
iterations is not known and the loop
continues until a condition is false.
#include <stdio.h>
int main() {
int i = 0;
while(i < 5) {
printf("i = %dn", i);
i++;
}
return 0;
}
Explanation: This loop prints
values from 0 to 4. It runs as
long as i < 5.
Syntax
6.
3. ‘do-while’ Loop● Similar to the ‘while’ loop
but guarantees that the
code block will execute at
least once.
#include <stdio.h>
int main() {
int i = 0;
do {
printf("i = %dn", i);
i++;
} while(i < 5);
return 0;
}
Explanation: This loop prints
values from 0 to 4. It runs at
least once and continues as
long as i < 5.
Syntax
7.
SUMMARY
In C programming,loops are used to repeat a set of instructions:
1. for loop: It implies that you already know how many times the loop
needs to run before the loop starts.
2. while loop: Repeats as long as a condition is true. Use it when you don't
know exactly how many times you'll need to repeat.
3. do-while loop: Similar to the while loop, but it always runs the
instructions at least once before checking the condition.