Loops in C | Types of C Loops

 

 Loops in C

The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are three types of loops used in the C language. In this part of the tutorial, we are going to learn all the aspects of C loops.

Loops in C


Why use loops in C language?

The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.

Advantage of loops in C


1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures (array or linked lists).

Types of C Loops

Loops in C
There are three types of loops in C language that is given below:
  1. For Loop:
  2. While Loop:
  3. Do-While Loop:
    1. For Loop:

      The for loop is often used when you know how many times you want to execute a block of code. It has the following syntax:
      c
      for (initialization; condition; increment/decrement) { // Code to be executed }
      1. Initialization: Typically used to initialize a loop control variable.
      2.Condition: Specifies the condition that must be true for the loop to continue executing.Increment/Decrement:
      3. Updates the loop control variable on each iteration.

      Example:

      c
      for (int i = 0; i < 5; i++) { printf("Iteration %d\n", i); }
    2. While Loop:

      The while loop is used when you want to execute a block of code as long as a certain condition is true. It has the following syntax:
      c
      while (condition) { // Code to be executed }

      Example:

      c
      int count = 0; while (count < 5) { printf("Count: %d\n", count); count++; }
    3. Do-While Loop:

      The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once before checking the condition. It has the following syntax:
      c
      do { // Code to be executed } while (condition);

      Example:

      c
      int x = 5; do { printf("x is %d\n", x); x--; } while (x > 0);
      Loops are fundamental for controlling program flow and executing repetitive tasks in C. Be cautious to avoid infinite loops, where the loop condition is never false, as they can lead to programs that never terminate. You should always ensure that the loop condition eventually becomes false to exit the loop.

Post a Comment

0 Comments