Thursday, October 11, 2018

Algorithm Repetition
Today in algorithm class i learn repetition.
so what is repetition?
Repetition is
  •   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
  • there are a couple of Repetition operation:
    • For
    • While
    • Do-while
1.For            Example of For:
  •   Program to print out numbers from 1 to 10 :
      
#include<stdio.h>
int main()
{
    int x;
    for( x = 1 ;  x <= 10 ;  x++ ) printf( "%d\n", x );
    return(0);
}
  • Program to print out numbers from 10 to 1  :

#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 can use “for-loop” by removing all parameters (exp1, exp2, exp3). To end the loop use break.  

  •  Nested Loop :
           Loop in a loop. The repetition Operation will start from the inner side loop.



2.While 
     while (exp) statements;
  • exp is Boolean expression. It will result in true (not zero) or false (equal to zero).
  • Statement will be executed while the exp is not equal to zero.
  • exp evaluation is done before the statements executed.
      Example :
while(product <= 1000) product = 2*product;



 








3.Do-while
  • Keep executing while statement is true
  • Statement evaluation done after executing the statement(s)
  Example:
  •  do{printf("%d\n",counter);}
      while(++counter <= 10);








  



Reference from binusmaya Algorithm and Programming class
resource session 9 (program control : repetition)