Looping in C
Looping in C
1. for loop
2. while loop
3. do...while loop
looping in C 1
However, if the test expression is evaluated to be true, statements inside the
body of the for loop are executed, and the update expression is updated.
for Loop
The syntax of the for loop is:
int main() {
int i;
1 2 3 4 5 6 7 8 9 10
while loop
The syntax of the while loop is:
looping in C 2
while (testExpression) {
// the body of the loop
}
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
}
return 0;
}
Output
1
2
3
4
5
looping in C 3
do...while loop
The do..while loop is similar to the while loop with one important difference. The
body of do...while loop is executed at least once. Only then, the test expression is
evaluated
do {
// the body of the loop
}
while (testExpression);
#include <stdio.h>
int main() {
double number, sum = 0;
printf("Sum = %.2lf",sum);
return 0;
}
looping in C 4
Entry Control Exit Control
The condition is tested at the beginning of The condition is tested at the end of the Loop
the Loop before the loop body executes. after the loop body is executed at least once.
The loop body may not be run if the The loop body runs at least once, even if the
condition is false. condition is false.
While Loop, For are some popular Entry Do-while is usually used as Exit Controlled
Controlled Loops. Loop.
Since the condition is tested at the Exit-controlled loops consistently execute the
beginning of the Loop, the loop body's loop body at least once, which can be less
code can be skipped if it is false. efficient if the condition is false.
looping in C 5