In C programming, a loop is a way to repeat a block of code multiple times. This is helpful when you want to do something again and again without writing the same code many times.

Types of Loops in C

There are three main types of loops in C:

  1. for loop – Best when you know how many times you want to repeat something.
  2. while loop – Good for repeating something as long as a condition is true.
  3. do-while loop – Similar to while, but it runs the code at least once before checking the condition.

How Each Loop Works

  1. for loop

    • Syntax:
      for (initialization; condition; increment/decrement) { // Code to repeat }
    • Example:

    • for (int i = 0; i < 5; i++) {
          printf("Hello\n");
      }

      • This loop prints "Hello" 5 times.
        • int i = 0; sets the starting value.
        • i < 5; is the condition, meaning the loop stops when i is 5.
        • i++ increases i by 1 each time.
    • while loop

      • Syntax:
      • while (condition) {
      •     // Code to repeat
      • }

      • Example:
      • int i = 0;
      • while (i < 5) {
      •     printf("Hello\n");
      •     i++;
      • }
      • This loop also prints "Hello" 5 times. Here, the loop continues as long as i < 5.
      • do-while loop

        • Syntax:
          do { // Code to repeat } while (condition);
        • Example:
          int i = 0;
          do {
              printf("Hello\n");
              i++;
          } while (i < 5);
            • This loop prints "Hello" 5 times, too. The main difference is it checks the condition after running the code, so it will always run at least once.

          Summary

          • Use for when you know how many times you want to loop.
          • Use while when you want to loop until a condition is no longer true.
          • Use do-while when you want to ensure the code runs at least once.

          Loops make programs shorter and more efficient by avoiding repeated code.

Comments

Post a Comment

Popular posts from this blog