C - Loops C-JK6
C - Loops C-JK6
C - Loops C-JK6
#include <stdio.h>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an
initialization and increment expression, but C programmers more commonly use the
for;;
construct to signify an infinite loop.
while loop in C
#include <stdio.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
do...while loop in C
• Unlike for and while loops, which test the loop condition at the top
of the loop, the do...while loop in C programming checks its
condition at the bottom of the loop.
• A do...while loop is similar to a while loop, except the fact that it is
guaranteed to execute at least one time.
• Syntax
• The syntax of a do...while loop in C programming language is −
do {
statement(s);
} while( condition );
int main () {
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
for loop in C
• After the body of the 'for' loop executes, the flow of control jumps back
up to the increment statement. This statement allows you to update any
loop control variables. This statement can be left blank, as long as a
semicolon appears after the condition.
• The condition is now evaluated again. If it is true, the loop executes and
the process repeats itself body of loop, then increment step, and then
again condition
• After the condition becomes false, the 'for' loop terminates.
Flow diagram- for loop
Example- for loop
#include <stdio.h>
int main () {
int a;
return 0;
}
• When the above code is compiled and executed, it produces the following result −
Nested loops in C
• C programming allows to use one loop inside another loop.
The following section shows a few examples to illustrate the
concept.
• Syntax
• The syntax for a nested for loop statement in C is as follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
Nested do...while loop
• The syntax for a nested do...while loop statement in C programming language
is as follows
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
• A final note on loop nesting is that you can put any type of loop inside any other
type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa.