Site icon SATMMER

Loop In C Programming

Loop In C Programming

Loops in C programming are essential constructs that allow you to repeatedly execute a block of code. There are three primary types of loops in C: for, while, and do-while. Each type has its specific use cases, and they share the common goal of automating repetitive tasks.

Loop : continously working at end point

1. For Loop:

The for loop is used when the number of iterations is known before entering the loop.(means that a for loop is typically chosen when you already know how many times you want the loop to execute before it starts running.) It consists of an initialization statement, a condition, and an increment or decrement statement.only row

syntex of for loop : for(intlization[starting];condition[ending];increment[1++]/decrement[1–]{

}

#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
printf(“Iteration %d\n”, i);
}

return 0;
}

In this example, the for loop will execute five times, printing “Iteration 1” to “Iteration 5.”

2. While Loop:

The while loop is used when the number of iterations is not known in advance. It continues to execute as long as the specified condition is true.only row

 

#include <stdio.h>

int main() {
int i = 1;

while (i <= 5) {
printf(“Iteration %d\n”, i);
i++;
}

return 0;
}

This example achieves the same result as the for loop but uses a while loop instead.

3. Do-While Loop:

The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once, as the condition is checked after the loop body.only row

#include <stdio.h>

int main() {
int i = 1;

do {
printf(“Iteration %d\n”, i);
i++;
} while (i <= 5);

return 0;
}

Even if the condition is false initially, the loop body will execute once.

4. Loop Control Statements:

a. Break Statement:

The break statement is used to exit a loop prematurely, regardless of whether the loop condition is still true.

#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
printf(“Iteration %d\n”, i);
}

return 0;
}

b. Continue Statement:

The continue statement is used to skip the rest of the loop body and move to the next iteration.

#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the rest of the loop body for i=3
}
printf(“Iteration %d\n”, i);
}

return 0;
}

Conclusion:

Loops are powerful tools in C programming for automating repetitive tasks and controlling the flow of a program. Choosing the appropriate loop construct depends on the specific requirements of your program. Whether it’s a for loop with a known number of iterations or a while loop for dynamic conditions, mastering these constructs is crucial for effective software development in C.

Exit mobile version