Control Flow: Loops (for, while, do-while)

Implementing repetitive tasks using `for`, `while`, and `do-while` loops.


The while Loop in C

What is the while Loop?

The while loop is a fundamental control flow statement in C programming that allows you to repeatedly execute a block of code as long as a specified condition remains true. It's crucial for tasks that require iteration based on a dynamic condition, such as processing data until a certain value is encountered, or performing an action until a flag is set.

while Loop Syntax and How it Works

The general syntax of a while loop in C is:

while (condition) {
    // Code to be executed repeatedly
} 

Here's how it works:

  1. The condition is evaluated. This condition can be any expression that evaluates to a boolean value (true or false). In C, 0 is considered false, and any non-zero value is considered true.
  2. If the condition is true (non-zero), the code inside the curly braces {} (the loop body) is executed.
  3. After the code inside the loop body has finished executing, the program returns to step 1, and the condition is evaluated again.
  4. Steps 2 and 3 are repeated as long as the condition remains true.
  5. If the condition is false (zero), the loop terminates, and the program continues execution at the statement immediately following the loop.

It's critical to ensure that the condition will eventually become false, otherwise the loop will run indefinitely (an infinite loop).

Examples of while Loops with Different Condition Structures

Example 1: Counting Up

This example demonstrates a while loop that counts from 1 to 5 and prints each number.

#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 5) {
        printf("%d\n", i);
        i++; // Increment i, otherwise the loop will be infinite!
    }

    return 0;
} 

Example 2: Reading Input Until a Specific Value is Entered

This example shows how to read integers from the user until the user enters -1.

#include <stdio.h>

int main() {
    int number;

    printf("Enter numbers (-1 to quit):\n");
    scanf("%d", &number); // Get the initial input

    while (number != -1) {
        printf("You entered: %d\n", number);
        printf("Enter another number (-1 to quit):\n");
        scanf("%d", &number); // Get the next input
    }

    printf("Done.\n");

    return 0;
} 

Example 3: Using a Boolean Flag

This example uses a boolean flag to control the loop. This approach can be useful when the condition for stopping the loop is determined within the loop itself.

#include <stdio.h>
#include <stdbool.h> // Include for the bool type

int main() {
    bool keep_going = true;
    int counter = 0;

    while (keep_going) {
        printf("Counter: %d\n", counter);
        counter++;

        if (counter > 10) {
            keep_going = false; // Stop the loop when counter exceeds 10
        }
    }

    printf("Loop finished.\n");

    return 0;
} 

Example 4: Checking for Prime Number (Simplified)

This is a simplified example and may not be fully optimized, but demonstrates how a while loop might be used within a prime number check.

 #include <stdio.h>
#include <stdbool.h>

int main() {
    int number;
    bool is_prime = true;
    int i = 2;

    printf("Enter a positive integer: ");
    scanf("%d", &number);

    if (number <= 1) {
        is_prime = false;
    } else {
        while (i * i <= number) { // Optimized condition: check up to the square root
            if (number % i == 0) {
                is_prime = false;
                break; // No need to continue checking if a divisor is found
            }
            i++;
        }
    }

    if (is_prime) {
        printf("%d is a prime number.\n", number);
    } else {
        printf("%d is not a prime number.\n", number);
    }

    return 0;
} 

These examples demonstrate the versatility of the while loop in C. Understanding how to use it effectively is crucial for writing more complex and dynamic programs.