Sunday, May 5, 2013

Loops in C

There are three types of loops, they are For Loop, While Loop and Do...While Loop.

Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming 


The syntax for a for loop is


for ( variable initialization; condition; variable update )
 {
  Code to execute while the condition is true
 } 

Example:
 
#include<stdio.h>
#include<conio.h>
void main()
{
    int x;
    for ( x = 0; x < 10; x++ )          /* The loop goes while x < 10, and x increases by one every loop*/
     
{
                                        /* Keep in mind that the loop condition checks 
        printf( "%d", x );                 the conditional statement before it loops again.
                                           consequently, when x equals 10 the loop breaks.
                                           x is updated before the condition is checked. */   
        
 }
    getch();
} 



While loop are very simple syntax is

while ( condition )
 {
  Code to execute while the condition is true
 }



Example:
 
 
#include<stdio.h>
#include<conio.h>
void main()
{ 
  int x = 0;                   /* Don't forget to declare variables */
  
  while ( x < 10 ) 
{                              /* While x is less than 10 */
      printf( "%d", x );
      x++;                     /* Update x so the condition can be met eventually */
 }
  getch();
} 






DO WHILE LOOP syntax is


do 
{
} 
while ( condition ); 
 
 
The condition is tested at the end of the block instead of the
beginning, so the block will be executed at least once. If the condition is
true, we jump back to the beginning of the block and execute it again. A
do..while loop is almost the same as a while loop except that the loop body is
guaranteed to execute at least once. A while loop says "Loop while the
condition is true, and execute this block of code", a do..while loop says
"Execute this block of code, and then continue to loop while the condition is
true".
 
 
Example:
 
 
#include <stdio.h>
#include<conio.h>
void main()
{
  int x;
  x = 0; 
  
do 
{
    printf( "Hello, world!\n" );        /* "Hello, world!" is printed at least one time
                                            even though the condition is false */
      
 } while ( x != 0 );
  getch();
} 

No comments:

Post a Comment