Loops are used in C to execute a block of code repeatedly. C supports three main types of loops:
The for loop is best used when the number of iterations is known. It has three parts: initialization, condition, and increment/decrement.
for (int i = 1; i <= 5; i++) {
printf("Value of i is: %d\n", i);
}
Explanation:
int i = 1 → Initialize counteri <= 5 → Loop continues as long as condition is truei++ → Increment counterThe while loop is used when the number of iterations is not known in advance. It checks the condition before each iteration.
int i = 1;
while (i <= 5) {
printf("Value of i: %d\n", i);
i++;
}
Note: If the condition is false at the beginning, the loop body won’t execute at all.
The do-while loop is similar to the while loop, but it checks the condition after executing the loop body at least once.
int i = 1;
do {
printf("Value of i: %d\n", i);
i++;
} while (i <= 5);
Note: The loop body will always run once, even if the condition is false.
| Loop Type | Condition Checked | Use Case |
|---|---|---|
| for | Before the loop starts | Known number of iterations |
| while | Before each iteration | Unknown iterations (user input, file reading) |
| do-while | After the loop body | At least one iteration is required |
Use a for loop to print numbers from 1 to 100.
Use a for or while loop and check if a number is even using modulus operator.
Input a number from the user and calculate its factorial using a for or while loop.
Input a number and print its multiplication table from 1 to 10 using a loop.
Use a loop to display the Fibonacci series (0, 1, 1, 2, 3, 5...) up to a given number of terms.
Input a number and reverse it using a while loop.
Input a number and count how many digits it has using a while loop.
Reverse the number using loop and compare it with original to check for palindrome.
Use loop to extract and add each digit of a number.
Input base and exponent. Use loop to multiply base exponent times.