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
- 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 :
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.
while(product <= 1000) product =
2*product;
3.Do-while
- Keep executing while statement is true
- Statement evaluation done after executing the statement(s)
- do{printf("%d\n",counter);}
Reference from binusmaya Algorithm and Programming class
resource session 9 (program control : repetition)
