Loops

Loops are used to repeat a block of code until a certain condition is met. They are a powerful tool that can be used to save code and perform complex tasks.

C programming language has three types of loops:

  • While loop
  • For loop
  • Do-while loop

While loop

The while loop is the simplest type of loop in C. It repeats a block of code as long as a given condition is true. The syntax for a while loop is as follows:

while (condition) {
  // block of code to be executed
}

The condition is evaluated before the block of code is executed. If the condition is true, the block of code is executed. The condition is then evaluated again, and the process repeats until the condition is false.

Here is an example of a while loop in C:

int i = 0;

while (i < 10) {
  printf("%d\n", i);
  i++;
}

This program will print the numbers from 0 to 9. The variable i is initialized to 0. The while loop will continue to execute as long as the value of i is less than 10. The block of code inside the while loop will print the value of i and then increment i by 1. When the value of i reaches 10, the condition will be false and the loop will terminate.

For loop

The for loop is a more versatile type of loop in C. It allows you to specify the initial value, the condition, and the update expression for the loop. The syntax for a for loop is as follows:

for (initialization; condition; update) {
  // block of code to be executed
}

The initialization expression is executed once, before the block of code is executed for the first time. The condition is then evaluated. If the condition is true, the block of code is executed. The update expression is then executed. The condition is then evaluated again, and the process repeats until the condition is false.

Here is an example of a for loop in C:

for (int i = 0; i < 10; i++) {
  printf("%d\n", i);
}

This program is the same as the previous example, but it uses a for loop instead of a while loop. The for loop is more concise and easier to read.

Do-while loop

The do-while loop is similar to the while loop, but the condition is evaluated after the block of code is executed. This means that the block of code will always be executed at least once, even if the condition is false. The syntax for a do-while loop is as follows:

do {
  // block of code to be executed
} while (condition);

Here is an example of a do-while loop in C:

int i = 0;

do {
  printf("%d\n", i);
  i++;
} while (i < 10);

This program will print the numbers from 0 to 9, even though the condition is false after the first iteration of the loop. This is because the block of code is executed before the condition is evaluated.

Loops are a powerful tool that can be used to save code and perform complex tasks. They are an essential part of any C programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *