C Language / Looping Statements

It is a part of the program (sequence of instructions / part of code) which is repeated to perform a particular task till a certain condition is meets. It is used save time, reduce errors and make code more readable.

While Loop
It is used to repeat a Block / Lines of code to be executed till it meets a certain condition. But I this loop first checks the condition of the loop and then it enters into the code block. It the condition is false it comes out of the loop.

While Loop Syntax
while (condition)
{
// code block to be executed
}

Sample Program to print 5 numbers Output

main()
{
int i = 0;
while (i < 5)
{
Printf(i);
i++;
}
}

0
1
2
3
4

The Do/While Loop
It is used to repeat a Block / Lines of code to be executed till it meets a certain condition.

Do/While Loop Syntax

do
{ // Block / Lines of code to be executed
}
while (condition);

Sample Program Output

main()
{
int i = 0;
do {
Printf(i);
i++;
}
while (i < 5);
}

0
1
2
3
4

For Loop
It is used to repeat a Block / Lines of code to be executed till it meets a certain condition. But in this loop first it enter into the code block and then increment / decrements the counters and thenchecks the condition of the loop till the condition is false it comes out of the loop.

For Loop Syntax
for (Initialization; Condition; Increment / Decrement)
{
// Block / Lines of code to be executed
}

Sample Program Output

main()
{
for (int i = 0; i < 5; i++)
{
Printf(i);
}
}
0
1
2
3
4

goto statement / unconditional branching statement in C Language
In goto control transfers to label and it is a unconditional branching statement used to got to a label when it finds a goto label name.

goto statement Syntax in C
goto Label_Name;
Statement1
Statement2
Statement3
--------------
Label_Name: C-statements

Sample Program Output

#include <stdio.h>
void main()
{
int number =1 ;
displaynos:
printf("%d\n",number);
number++;
if(number<=5)
goto displaynos;
}

1
2
3
4
5


Home     Back