What I learn from today class are repetition in programming to control the program. Repetition in programming can also be named looping or iteration. Go to function can also use to control the program, but could make the program more messy.
There are 3 type of repetition that we learned, it is:
- For
- While
- Do While
The difference between While and Do While is :
- While repetition can only make the statement executed when the condition met. It check the condition first, then execute the instruction and repeat the action.
- Do While repetition would still execute the statement at least once even when the condition doesn't met. It execute the instruction first, then check the condition and repeat the action.
For Syntax :
for(exp1; exp2; exp3) statement;
or
for(exp1; exp2; exp3) {
statement 1;
statement 2;
. . . . . . . . . .
}
exp1 = Initialization
exp2 = Condition
exp3 = Increment or Decrement
for example :
1. Reverse String
. . . . . . . . .
void reverse (char ss[])
{
int c, i, j;
for(i = 0; j = strlen(ss) - 1; i++, j--) {
c = ss[i];
ss[i] = ss [j];
ss[j] = c;
}
}
. . . . . . . .
2. Create 10 asterisk (*) symbol
. . . . . . . . . .
for(int i = 10; i > 0; i++) {
printf("*");
}
. . . . . . . . . . .
3. Create x*y asterisk (*) symbol
. . . . . . . . . . .
for (int x = 0; x < a; x++) {
for (int y = 0; y < a; y++) {
printf("*");
}
printf("\n");
}
. . . . . . . . . . . .
break function used to break the infinite loop.
Note : to compile the input repeatedly, While repetition can be added before scanf function, provided that conditions are given.
No comments:
Post a Comment