Repetition
- Michael Felix

- Dec 12, 2018
- 2 min read
Updated: Dec 13, 2018
Repetition, or better known as looping, is the process of repeating statements to be more simple and efficient. For example we want to print numbers from 1-100, of course it will be very complicated if done 100 times. However, we can do it with just a few lines of code with looping. There are 3 types of repetitions in C, including Do, Do While, and For.
DO WHILE
On looping using DO WHILE, the program statement will be repeated repeatedly as long as the conditions in WHILE are still fulfilled or true. The loop will stop if the condition conditions in WHILE are incorrect. In the DO WHILE loop, the program statement will be run at least once before checking the condition conditions in WHILE.
do{
//statement
}while(condition);Example
#include <stdio.h>
int main(){
// do it will make a statement ONCE FIRST then it will check its condition BELOW, if TRUE then CONTINUE if FALSE then STOP
int number;
//asking for input number
printf("Enter number : ");
scanf("%d", &number);
fflush(stdin);
//initialization value i = 1
int i=1;
//do it will make a statement ONCE FIRST then it will check its condition BELOW, if TRUE then CONTINUE if FALSE then STOP
do{
printf("%d\n",i);
i++;
}while(i<=number);
getchar();
return 0;
}WHILE
On looping using WHILE, the program statement will also be executed repeatedly as long as the condition conditions in WHILE are still true. The loop will stop if the WHILE requirement is incorrect.
while(condition){
//statement
}Example
#include <stdio.h>
int main(){
//while will check the condition first before running the statement
int number;
//asking for input numbers
printf("Enter Number : ");
scanf("%d", &number);
fflush(stdin);
//initialization value i
int i=1;
//while will check the condition first before running the statement
//will continue to repeat until i is smaller equal to the number (user input);
while(i<=number){
//print number
printf("%d\n", i);
i++;
}
getchar();
return 0;
}FOR
Repeat FOR has a special looping concept when compared to WHILE and DO WHILE. In the FOR loop, variable initialization, number requirements and operations are written in one group and separate from the program statement that will be executed.
The program statement will be repeated as long as the conditions of the condition are still fulfilled or true. Repetition of FOR is done to summarize the loop writing using WHILE when it is known or determined the number of repetitions.
for (first value; check value condition; changing value operation) {
//statement
}Example
#include <stdio.h>
int main(){
int number;
//asking for input numbers
printf("Enter Number : ");
scanf("%d", &number);
fflush(stdin);
//initial value 1, will keep repeating until i is smaller equal to number (user input)
for(int i=1; i<=number; i++){
//print number
printf("%d\n", i);
}
getchar();
return 0;
}
Comments