Simple Tutorials for Smart Learning
Loops in C are used to execute a block of code repeatedly as long as a given condition is true. C supports three primary types of loops:
for loop – when you know how many times to loop
for
while loop – when you don’t know how many times to loop
while
do-while loop – when the loop must run at least once
do-while
for (initialization; condition; update) { // Code block to execute }
#include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { printf("Count: %d\n", i); } return 0; }
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
while (condition) { // Code block }
#include <stdio.h> int main() { int i = 1; while (i <= 5) { printf("Count: %d\n", i); i++; } return 0; }
This loop always executes at least once, even if the condition is false on the first check.
do { // Code block } while (condition);
#include <stdio.h> int main() { int i = 1; do { printf("Count: %d\n", i); i++; } while (i <= 5); return 0; }
break
continue
=
==
{}
#include <stdio.h> int main() { int sum = 0, i = 1; while (i <= 100) { sum += i; i++; } printf("Sum = %d\n", sum); return 0; }
Sum = 5050