Sunday, February 20, 2011

LOOPS IN C LANGUAGE

Why we use loops in C language or any language ? 

             Look friends to understand the looping concept you need to know the importance of  loop , loops are use to perform any task repeatedly and take decision according to condition set in looping , loops are always a part of a big program . 

Lopping in C
Loops :- Loops generally possess two parts one is body of loop and another is called control statement .Control statement decides the category of loop,there for control statement is classified as entry-control loop or exit-control loop.
Loops generally posses few steps :-
  • declaration and initialization of condition variable
  • writhing condition statement in loop
  • putting increment or changing condition of variable

Loops provided by C language are as follows:-
  • While loop
  • Do loop
  • for loop
While Loop
format of while loop

While (test condition )
{
Body of loop
}

example-

int i=1 sum=0; /* initialization */
While (i<=10 ) /* condition */
{
sum=i+1;
i=i+1; /* increment */
}

Do Loop
format of do loop:-

do
{
     Body of loop
}
While (test condition );
note:- this will execute the loop 1st time and then from next time will check the condition of while till condition does not goes false .
Example:-
int I;
do
{
   printf(“Enter any number”)
   scanf(“%d”&i);
   printf(“number=%d”,i);
}
While (i>=1);

For Loop:-
for loop provides the best control structure and reduce the code length of a user.
Format of for loop :-
for (initialization;condition; increment)
{
   body of loop;
}

example:-
int I;
for (i=1;i<=5; i++)
{
     printf(“*”);
}
printf(“\n”);

this will print 5 star in a column every star on new line .   

No comments:

Post a Comment