Skip to content

Loops in C

Loops are control structures that allow the execution of a block of code repeatedly as long as a specified condition is met.

Common types of loops in C are: for, while, and do-while.

  • for Loop: Repeats a block of code a specific number of times. It is also known as Entry-Controlled loop as the condition is checked before the execution of code inside the loop body .
for (initialization; condition; increment/decrement) {
// code block
}

  • while Loop: Repeats a block of code while a condition is true. It is also Entry-Controlled loop
while (condition) {
// code block
}

  • do-while Loop: Executes code block at least once, then repeats while condition is true. It is also known as Exit-Controlled loop as the condition is checked after loop is executed
do {
// code block
} while (condition);

#include <stdio.h>
int main(){
printf("\n\n*******Loop in C*********\n\n");
int index = 0;
for(int j = 0; j <= 100; j++) {
//FOR LOOP => A for loop is a repetition control structure that allows us to efficiently
// write a loop that will execute a specific number of times.
printf("%d\n", j);
}
while (index <= 10) {
// WHILE LOOP => The while loop allows code to be executed multiple times, depending upon a
// boolean condition. It is terminated on the basis of the Boolean (true or false) test condition.
printf("%d\n", index);
index++;
}
int j=0;
do {
printf("do while loop is running");
// DOWHILE LOOP => The main difference between the do-while loop and while loop is that, in the do-while loop,
// the condition is tested at the end of the loop body, whereas the other two loops are entry controlled loops.
} while (j>5);
// Note: In do-while loop, the loop body will execute at least once irrespective of the condition.
return 0;
}