Loops in C Programming for Beginners with Examples

Loops in C Programming

Loops in C programming are used to execute a block of code repeatedly until a condition is satisfied. They help reduce code repetition and make programs efficient.

Types of Loops in C

  • for loop
  • while loop
  • do-while loop

1. for Loop

The for loop is used when the number of iterations is known.

Syntax:


for(initialization; condition; update) {

   // code

}

Example:


#include <stdio.h>

int main() {

   int i;

   for(i = 1; i <= 5; i++) {

      printf("%d\n", i);

   }

   return 0;

}

This program prints numbers from 1 to 5.


2. while Loop

The while loop executes code while the condition is true.

Syntax:


while(condition) {

   // code

}

Example:


#include <stdio.h>

int main() {

   int i = 1;

   while(i <= 5) {

      printf("%d\n", i);

      i++;

   }

   return 0;

}


3. do-while Loop

The do-while loop executes the code at least once, even if the condition is false.

Syntax:


do {

   // code

} while(condition);

Example:


#include <stdio.h>

int main() {

   int i = 1;

   do {

      printf("%d\n", i);

      i++;

   } while(i <= 5);

   return 0;

}


Why Loops Are Important

  • Reduce code repetition
  • Make programs efficient
  • Used in almost every real-world program

Conclusion

Loops help execute code multiple times based on conditions. After learning loops, the next step is control statements like break and continue.

Comments

Popular posts from this blog

Structures in C Programming with Examples

What is C programming?

Arrays in C Programming for Beginners with Examples