C Tutorial



LOOPS IN C


Loops in C

Loops are used to repeatedly execute a block of code as long as a specified condition is true. In C, there are three main types of loops:

  • For Loop
  • While Loop
  • Do-While Loop

🔄 For Loop

The for loop is used when the number of iterations is known beforehand. It includes three parts: initialization, condition, and increment/decrement.

for (initialization; condition; increment/decrement) {
    // Code to be executed
}
  

Example:

#include 

int main() {
    for (int i = 1; i <= 5; i++) {
        printf("%d\n", i);
    }
    return 0;
}
  

🔄 While Loop

The while loop is used when the number of iterations is not known in advance, but the loop should continue as long as a condition remains true.

while (condition) {
    // Code to be executed
}
  

Example:

#include 

int main() {
    int i = 1;
    while (i <= 5) {
        printf("%d\n", i);
        i++;
    }
    return 0;
}
  

🔄 Do-While Loop

The do-while loop is similar to the while loop, but the condition is checked after the code is executed. This ensures that the loop is always executed at least once.

do {
    // Code to be executed
} while (condition);
  

Example:

#include 

int main() {
    int i = 1;
    do {
        printf("%d\n", i);
        i++;
    } while (i <= 5);
    return 0;
}
  

📝 Try It Yourself

  1. Write a program that prints the first 10 natural numbers using a for loop.
  2. Write a program that calculates the sum of numbers from 1 to 100 using a while loop.
  3. Write a program that prints all even numbers from 1 to 20 using a do-while loop.

❌ Common Mistakes

  • 🚫 Forgetting to update the loop variable in while or do-while loops, leading to infinite loops.
  • 🚫 Incorrect condition in the loop, which may cause the loop to not execute or execute an incorrect number of times.
  • 🚫 Missing break or continue statements to control loop flow in certain situations.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review