Home » Use Of While Loop In C++

Use Of While Loop In C++

Use Of While Loop In C++

Introduction

In C++, the while loop is a control flow statement used for iterating over a block of code as long as a specified condition evaluates to true. It provides a flexible way to execute code repeatedly based on a condition without the need for a predetermined number of iterations.

Syntax

The syntax of the while loop in C++ is straightforward

while (condition) {
    // Code to be executed as long as the condition is true
}
C++
  • condition: This is a boolean expression evaluated before each iteration of the loop. If the condition evaluates to true, the loop body is executed. If it evaluates to false, the loop terminates.

Key Characteristics

  • Dynamic Condition: Unlike the for loop where the number of iterations is determined upfront, the while loop’s condition is evaluated before each iteration. This allows for dynamic control flow based on runtime conditions.
  • Entry-controlled Loop: The while loop is entry-controlled, meaning the condition is evaluated before the loop body executes. If the condition is initially false, the loop body will not execute at all.
  • Potential for Infinite Loops: Care must be taken to ensure that the condition eventually evaluates to false to prevent infinite loops. Without proper handling, an infinite loop can lead to program crashes or unexpected behavior.

Common Usage Scenarios

  • Iterating Until a Condition is Met: The while loop is often used when the number of iterations is not known in advance and depends on runtime conditions.
  • Input Validation: It is commonly employed in input validation scenarios, where the loop continues until valid input is received.
  • Processing Data Streams: while loops are suitable for processing data streams, reading files, or handling network connections until a termination condition is encountered.

Flow chart of while loop

Real world example of while loop

A real-world example of using a while loop in C++ could involve reading user input until a specific condition is met. Let’s consider a scenario where a user is prompted to enter a password, and the program continues to prompt the user until the correct password is entered. Here’s how it could be implemented using a while loop:

#include <iostream>
#include <string>

int main() {
    // Define the correct password
    std::string correctPassword = "password123";

    // Variable to store user input
    std::string userInput;

    // Prompt the user to enter the password
    std::cout << "Enter the password: ";

// Use a while loop to repeatedly prompt the user until the correct password is entered
    while (true) {
        // Read user input
        std::cin >> userInput;

        // Check if the entered password matches the correct password
        if (userInput == correctPassword) {
            std::cout << "Login successful. Welcome!\\\\n";
            break; // Exit the loop if the password is correct
        } else {
            std::cout << "Incorrect password. Please try again: ";
        }
    }

    return 0;
}

C++

In this Example

  • The program prompts the user to enter a password.
  • It then enters a while loop that continues indefinitely (while (true)).
  • Inside the loop, it reads the user’s input using std::cin.
  • If the entered password matches the correct password (correctPassword), the program outputs a success message and exits the loop using the break statement.
  • If the entered password is incorrect, the program prompts the user to try again.

This example demonstrates how a while loop can be used to repeatedly perform an action (prompting the user for input) until a specific condition (correct password entry) is met. It’s a common pattern for interactive programs where user input validation is required.

Examples Of while Loop In C++

Example 1: Printing Numbers from 1 to 5

#include <iostream>

int main() {
    int i = 1; // Initialization

    // While loop to print numbers from 1 to 5
    while (i <= 5) { // Condition
        std::cout << i << " ";
        ++i; // Update
    }

    std::cout << std::endl;

    return 0;
}

C++

Expected Output:

1 2 3 4 5
C++

Example 2: Calculating Factorial

#include <iostream>

int main() {
    int n = 5; // Number for which factorial is calculated
    int factorial = 1;
    int i = 1; // Initialization

    // While loop to calculate factorial
    while (i <= n) { // Condition
        factorial *= i;
        ++i; // Update
    }

    std::cout << "Factorial of " << n << " is: " << factorial << std::endl;

    return 0;
}

C++

Expected Output:

Factorial of 5 is: 120
C++
Example 3: Counting Down from 10 to 1
#include <iostream>

int main() {
    int count = 10; // Initialization

    // While loop to count down from 10 to 1
    while (count >= 1) { // Condition
        std::cout << count << " ";
        --count; // Update
    }

    std::cout << std::endl;

    return 0;
}

C++

Expected Output:

10 9 8 7 6 5 4 3 2 1
C++
Example 4: Sum of Even Numbers from 1 to 20
#include <iostream>

int main() {
    int sum = 0;
    int num = 2; // Initialization

    // While loop to calculate sum of even numbers from 1 to 20
    while (num <= 20) { // Condition
        sum += num;
        num += 2; // Update to next even number
    }

    std::cout << "Sum of even numbers from 1 to 20 is: " << sum << std::endl;

    return 0;
}
C++

Expected Output:

Sum of even numbers from 1 to 20 is: 110
C++

These examples demonstrate the versatility of while loops in C++ for various tasks such as iterating, counting, calculating factorial, and summing numbers.

Conclusion

The while loop in C++ is a fundamental control flow statement used for executing a block of code repeatedly as long as a specified condition remains true. Throughout this discussion, we’ve covered several important aspects of the while loop:

  1. Structure and Syntax:
    • The while loop follows a simple structure: while (condition) { /* loop body */ }.
    • The loop continues to execute the loop body as long as the condition evaluates to true.
  2. Dynamic Iteration:
    • Unlike for loops, which have a predetermined number of iterations, while loops are suitable when the number of iterations is not known beforehand and depends on a runtime condition.
  3. Entry-Controlled Loop:
    • The while loop is entry-controlled, meaning the loop condition is evaluated before entering the loop body. If the condition is initially false, the loop body will not execute at all.
  4. Handling Infinite Loops:
    • Care must be taken to ensure that the loop condition eventually evaluates to false to prevent infinite loops. Infinite loops can lead to program crashes or unexpected behavior.
  5. Common Usage Scenarios:
    • while loops are often used when repeated execution is required until a certain condition is met, such as input validation, data processing, or interactive menu-driven programs.
  6. Versatility:
    • The while loop is a versatile construct that can be combined with other control flow statements and used in various scenarios to achieve complex programming tasks.

Frequently asked Questions

1. What is a while loop in C++?

A while loop is a control flow statement used for executing a block of code repeatedly as long as a specified condition evaluates to true.

2. How does the while loop work in C++?

The while loop evaluates the condition before each iteration. If the condition is true, the loop body is executed. If the condition is false, the loop terminates.

3. What happens if the condition of a while loop is initially false?

If the condition of a while loop is initially false, the loop body will not execute, and the program will continue with the statement following the while loop.