Loops in C Programming

Know more in Detail

Loops are used in C to execute a block of code repeatedly. C supports three main types of loops:

1. for Loop

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:

2. while Loop

The 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.

3. do-while Loop

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.

Comparison Table

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

C Programming - Loop Assignments

1. Print numbers from 1 to 100 using a loop.

Use a for loop to print numbers from 1 to 100.

2. Print even numbers between 1 to 50 using a loop.

Use a for or while loop and check if a number is even using modulus operator.

3. Find the factorial of a number.

Input a number from the user and calculate its factorial using a for or while loop.

4. Display multiplication table of a number.

Input a number and print its multiplication table from 1 to 10 using a loop.

5. Print Fibonacci series up to n terms.

Use a loop to display the Fibonacci series (0, 1, 1, 2, 3, 5...) up to a given number of terms.

6. Reverse a number using loop.

Input a number and reverse it using a while loop.

7. Count number of digits in an integer.

Input a number and count how many digits it has using a while loop.

8. Check whether a number is palindrome or not.

Reverse the number using loop and compare it with original to check for palindrome.

9. Find sum of digits of a number using loop.

Use loop to extract and add each digit of a number.

10. Find the power of a number using loop.

Input base and exponent. Use loop to multiply base exponent times.