Sei sulla pagina 1di 3

for(i=1;i<=10;i++)

{
printf("\n%d",i);
}

int i=1;
while(i<=10)
{
printf("\n%d",i);
i++;
}

int i=1;
do
{
printf("\n%d",i);
i++;
}while(i<=10);

While loop:

syntax of while:

initial value;
while(terminating condition)
{
statements...
increment/decrement;
}

here initial value is the start value with which the loop starts
terminating condition is that value which is checked everytime to proceed further
and as soon as it surpasses, loop exits and control is transferred to the statement
immediately after loop body
increment or decrement may be used depending upon the requirement, increment is
used in positive loops (low to high value) and decrement is used in negative loops
(high to low value)

example:
int i=1;
while(i<=10)
{
printf("%d\t",i);
i++;
}

prints all the numbers starting from 1 till 10 in one line with gaps in between
(positive loop)

int i=10;
while(i>=1)
{
printf("%d\t",i);
i--;
}

prints all the numbers starting from 10 till 1 in one line with gaps in between
(negative loop)
int i=2;
while(i<=10)
{
printf("%d\t",i);
i+=2;
}

prints all the even numbers starting from 2 till 10 in one line with gaps in
between, here we have given increment of 2 everytime, i+=2 means i=i+2

int i=1;
while(i<=10)
{
printf("%d\n",i);
i++;
}

prints all the numbers starting from 1 till 10 in different lines

int i=1;
while(i<=10)
{
printf("%d",i);
i++;
}

prints all the numbers starting from 1 till 10 without any gaps in between

Do while loop:

syntax of do while:

initial value;
do
{
statements...
increment/decrement;
}while(terminating condition);

here initial value is the start value with which the loop starts
increment or decrement may be used depending upon the requirement, increment is
used in positive loops (low to high value) and decrement is used in negative loops
(high to low value)
terminating condition is that value which is checked everytime to proceed further
and as soon as it surpasses, loop exits and control is transferred to the statement
immediately after loop body but here the loop executes at least once since the
condition is checked at the end

example:

int i=1;
do
{
printf("%d\t",i);
i++;
}while(i<=10);

prints all the numbers starting from 1 till 10 in one line with gaps in between
(positive loop)
int i=10;
do
{
printf("%d\t",i);
i--;
}while(i>=1);

prints all the numbers starting from 10 till 1 in one line with gaps in between
(negative loop)

1 2 3 4 5 6 7 8 9 10

int i=2;
do
{
printf("%d\t",i);
i+=2;
}while(i<=10);

prints all the even numbers starting from 2 till 10 in one line with gaps in
between, here we have given increment of 2 everytime, i+=2 means i=i+2

2 4 6 8 10

int i=1;
do
{
printf("%d\n",i);
i++;
}while(i<=10);

prints all the numbers starting from 1 till 10 in different lines

1
2
3
4
5
6
7
8
9
10

int i=1;
do
{
printf("%d",i);
i++;
}while(i<=10);

prints all the numbers starting from 1 till 10 without any gaps in between

12345678910

Potrebbero piacerti anche