Sei sulla pagina 1di 3

Loops are used to perform a repetitive task a given number of times

Whatever statements or commands are given inside loop are repeated given number of
times

There are three types of loops:


1- for
2- while
3- do while

for loop is used when we know exactly how many times the task will be repeated.

while loop is used when we don't know exactly how many times the loop will be
repeated and when to quit

do while works exactly the same as while, the only difference being here the
terminating condition is checked at the exit of loop

for and while are called entry controlled loops, ie, the condition will be checked
before entering into the loop, if the condition is false, the loop doesn't perform

do while is called exit controlled loop, ie, the condition will be checked when we
exit the loop, therefore the loop performs at least once whether the condition is
true or false

syntax of for:

for(initial value;terminating condition;increment/decrement)


{
statements...
}

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;
for(i=1;i<=10;i++)
{
printf("%d\t",i);
}
prints all the numbers starting from 1 till 10 in one line with gaps in between
(positive loop)

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

int i;
for(i=2;i<=10;i+=2)
{
printf("%d\t",i);
}
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;
for(i=1;i<=10;i++)
{
printf("%d\n",i);
}
prints all the numbers starting from 1 till 10 in different lines

int i;
for(i=1;i<=10;i++)
{
printf("%d",i);
}
prints all the numbers starting from 1 till 10 without any gaps in between

1- Print the number, square and cube of all the numbers from 1 to 10
2- Print all the odd numbers from 500 to 1000.
3- Add all the numbers between 10 to 100 and print their sum
4- Check and print all the numbers between 1 to 10 whether it is even or odd
5- Print your name 5 times

Answers:
1- int i;
for(i=1;i<=10;i++)
{
printf("%d\t%d\t%d\n",i,i*i,i*i*i);
}

2- int i;
for(i=501;i<1000;i+=2)
{
printf("%d\t",i);
}

3- int i,s=0;
for(i=10;i<=100;i++)
{
s=s+i;
}
printf("\n%d",s);
}

4- int i;
for(i=1;i<=10;i++)
{
if(i%2==0)
{
printf("\n%d is even",i);
}
else
{
printf("\n%d is odd",i);
}
}
5- int i;
char name[10]="Namit";
for(i=1;i<=5;i++)
{
printf("\n%s",name);
}

Potrebbero piacerti anche