Wednesday, October 10, 2018

Program Control : Repetition

What is repetition?
         Repetition means one or more instruction repeated for certain amount of time. Number of repetition can be predefined (hard-coded in program) or defined later at run time. Some of the repetition/looping operation are for, while, do-while. 

Ex of for :
     Syntax:
for(exp1; exp2; exp3) statement;
or:
for(exp1; exp2; exp3){
  statement1;
  statement2;
  …….
 }
exp1 :  initialization
exp2 :  conditional
exp3 :  increment or decrement
exp1, exp2 and exp3 are optional

exp1 and exp3 can consist of several ecpression sepparated with comma.

Ex :
void reverse(char ss[])
{
    int c,i,j;
    for(i=0, j=strlen(ss)-1; i<j; i++, j--){
        c=ss[i];
        ss[i]=ss[j];
        ss[j]=c;
    }
}
flow chart of for statement :

Image result for flow chart of for loop

example of a program to print out numbers from 1 to 10

#include <stdio.h>
int main()
{
      int x;
      for( x = 10 ; x <= 1 ; x--)
      printf("%d\n",  x);
      return 0;
}

   Infinite Loop
Loop with no stop condition using "for-loop" by removing all parameters (exp1,ep2,exp3).
To end the loop use break.

   Nested Loop
Loop in a loop. The repetition operation will start from the inner side loop

here are the example of Nested Loop :
    in C
int x, y;
for(x = 1 ; x <= 5 ; x++)
      for(y = 5 ; y >= 1 ; y--)
            printf("%d %d ",x ,y);
   in C++
for(int x = 1 ; x <= 5 ; y >= 1 ; y--)
      for(int y = 5 ; y >= 1 ; y--)
            printf("%d %d ", x , y);
Output = 1 5 1 4 1 3 .. 2 5 2 4 .. 5 1


Ex of while :


Syntax :
while (exp) statements;
or:
while(exp){
  statement1;
  statement2;
   …..
}


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

flow chart of WHILE Statement :
Image result for flow chart of while loop



No comments:

Post a Comment