Loops in C
Loops in C
Loops in C
Language
Loop
-it is a block of statement that
performs set of instructions. In loops
Repeating particular portion of the
program either a specified number of
time or until a particular no of
condition is being satisfied.
C programming has three types of loops:
1. for loop
2. while loop
3. do...while loo
for loop
A for loop is a repetition control structure that
allows you to efficiently write a loop that needs
to execute a specific number of times.
In a program, for loop is generally used when
number of iteration are known in advance. The
body of the loop can be single statement or
multiple statements.
Syntax:
for(exp1;exp2;exp3)
{
Statement;
}
or
for(initialized; condition; increment/iteration)
{
Statement;
}
Here is the flow of control in a for loop −
• 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.
• 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 flow of control
jumps to the next statement just after the for loop.
• After the body of the for loop executes, the flow
of control jumps back up to the increment
statement. 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.
Example 1
#include <stdio.h>
int main()
{
int x;
for(x=1;x<10;i++)
{
Printf(“ %d ”, x);
}
}
Output:-1 2 3 4 5 6 7 8 9
C nested for Loop
Using a for loop within another for loop is said
to be nested for loop. In nested for loop one or
more statements can be included in the body of
the loop. In nested for loop, the number of
iterations will be equal to the number of
iterations in the outer loop multiplies by the
number of iterations in the inner loop.
nested for Loop Syntax
#include <stdio.h>
int main()
{
int x,y;
for(x=1;x<=2;x++)
{
for(y=1;y<=3;y++)
printf(“%d”, y);
}
}