Saturday, 10 January 2015

All About Loop in C

All About Loop in C

Programming languages provide various control structures that allow to execute a statement or group of statements multiple time.  general form of a loop statement in most of the programming languages.




There may be  a situation in your programming you need to execute a block of code several numbers of times.

A loop statement allows us to execute a statement or group of statements multiple times sequentially.


Loop Type
Description
For loop
Allows code to be repeatedly executed. A kind of control statement for specifying iteration
While loop
Repeats a statement or group of statements while a given condition is true
Do..while loop
A do while loop is a control flow statement that executes a block of code at least once
Nested loops
You can use one or more loop inside any another while, for or do..while loop.


For loop basic structure:

The “for loop” loops from one number to another number and increases by a specified value each time.
The “for loop” uses the following structure:


for (Start value; continue or end condition; increase value)
{
Body......

}


               
                #include<stdio.h>

                int main()
                {
                                int i;
                                for (i = 0; i < 10; i++)
                                {
                                printf ("introduction of for loop\n");
                              
                                }
                return 0;
                }
               

Basic Structure of while loop:

You can repeat the statements in a loop structure until a condition is True

while(condition)
{
   statement(s);
}


Example:


#include <stdio.h>

int main ()
{
   /* local variable definition */
   int a = 10;

   /* while loop execution */
   while( a < 20 )
   {
      printf("value of a: %d\n", a);
      a++;
   }

   return 0;
}



BASIC STRUCTURE OF DO WHILE LOOP

do {
   do_work();
} while (condition);


Is equivalent to



do_work();
while (condition) {
   do_work();
}


In this manner, the do ... while loop saves the initial "loop priming" with do_work(); on the line before the while loop.

As long as the continue statement is not used, the above is technically equivalent to the following (though these examples are not typical or modern style):

while (true) {
   do_work();
   if (!condition) break;
}

Or

LOOPSTART:

   do_work();
   if (condition)
 goto LOOPSTART;



……………………..
Example:

#include <stdio.h>
 main()
{
    int i = 10;

    do{
       printf("Hello %d\n", i );
       i = i -1;
    }while ( i > 0 );

}

No comments:

Post a Comment