Zone Of Makos

Menu icon

Entry Controlled Loops in C

Entry controlled loops are a type of loop in C programming where the loop condition is checked before entering the loop body. If the condition is true, the loop body is executed, and if the condition is false, the loop is skipped entirely. Entry controlled loops provide a way to repeatedly execute a block of code as long as a specific condition is true. In this lesson, we'll explore the usage of entry controlled loops in C, provide examples, and discuss their benefits.

Usage of Entry Controlled Loops

Entry controlled loops are commonly used when you know the number of iterations in advance or when the loop condition is checked before executing the loop body. The most common entry controlled loop in C is the while loop, but you can also use the for loop with appropriate conditions to achieve entry controlled behavior.

While Loop:


while (condition) {
    // Loop body
}

For Loop:


for (initialization; condition; increment/decrement) {
    // Loop body
}

Examples

Let's look at a couple of examples to illustrate the usage of entry controlled loops in C.

Example 1: Printing Numbers


#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 5) {
        printf("%d ", i);
        i++;
    }

    return 0;
}

In this example, the while loop is used to print the numbers from 1 to 5. The loop condition checks if i is less than or equal to 5. If true, the loop body is executed, which prints the value of i and increments it by 1. The loop continues until the condition becomes false.

Example 2: Sum of Even Numbers


#include <stdio.h>

int main() {
    int sum = 0;

    for (int i = 2; i <= 10; i += 2) {
        sum += i;
    }

    printf("Sum of even numbers: %d\n", sum);

    return 0;
}

In this example, the for loop is used to calculate the sum of even numbers from 2 to 10. The loop initializes i to 2, checks if i is less than or equal to 10, and increments i by 2 in each iteration. The loop body adds the value of i to the sum variable. The loop continues until the condition becomes false.

Conclusion

Entry controlled loops in C provide a way to repeatedly execute a block of code as long as a specific condition is true. The while and for loops are commonly used entry controlled loops in C. They allow you to control the number of iterations and perform tasks efficiently. By understanding and utilizing entry controlled loops, you can write more flexible and powerful programs in C.