Looping Statements in C - 6 Looping Statements and Usage (For, While, Do... While
Looping Statements in C - 6 Looping Statements and Usage (For, While, Do... While
Loop Types in C:
while loop
for loop
do-while loop
FOR LOOP
SYNTAX
The syntax of a for loop in C programming
language is
for (initialization; condition; increment/decrement ) {
statement(s);
}
INITIALIZATION:
The initialization step is executed first, and only
once. This step allows you to declare and initialize
any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.
CONDITION:
Next, the condition is evaluated. If it is true, the
body of the
loop is executed. If it is false, the body of the loop
does not execute and the flow of control jumps to
the next statement just after the 'for' loop.
INCREMENT:
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.
FLOW DIAGRAM
#include <stdio.h>
int main () {
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}
return 0;
}
OUT PUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
INFINITY PROGRAM:
#include <stdio.h>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;}
#include<stdio.h>
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=10;i++){
printf("%d \n",(number*i));
}
return 0;
}
OUTPUT:
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
WHILE LOOP
SYNTAX
The syntax of a while loop in C programming language is
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of
statements. The condition may be any expression, and true is
any nonzero value. The loop iterates while the condition is true.
FLOW DIAGRAM:
#include <stdio.h>
int main () {
return 0;}
OUT PUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
DO-WHILE LOOP
SYNTAX
The syntax of a do...while loop in C programming
language is
do {
statement(s);
} while( condition );
FLOW DIAGRAM:
#include <stdio.h>
int main () {
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;}
OUTPUT:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19