*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
*Repetition/looping operation:
–for
–while
–do-while
Example of using 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
Example of using For :
*Program to print out even numbers :
#include<stdio.h>
int main(){
for(int i=1;i<10;i++){
if(i%2==0){
printf("Bilangan Genap : %d\n",i);
}
}
return 0;
}
int main(){
for(int i=1;i<10;i++){
if(i%2==0){
printf("Bilangan Genap : %d\n",i);
}
}
return 0;
}
Flowchart of For Statement :
For has nested loop(loop in a loop),the repetition operation will start
from the inner side loop.
Example of Nested Loop :
#include<stdio.h>
int main(){
int a,b;
for(int i=1;i<10;i++){
for(int j=0;j<i;j++){
printf("*");
}
printf("\n");
}
return 0;
}
Output :
*
**
***
****
*****
******
*******
********
*********
int main(){
int a,b;
for(int i=1;i<10;i++){
for(int j=0;j<i;j++){
printf("*");
}
printf("\n");
}
return 0;
}
Output :
*
**
***
****
*****
******
*******
********
*********

No comments:
Post a Comment