Geek Slack

Learn C++
    About Lesson


    C++ While Loop


    C++ While Loop

    The while loop in C++ repeatedly executes a block of statements as long as a specified condition is true. It is useful when you need to iterate based on a condition that is evaluated before each loop iteration.

    1. Basic while Loop

    The basic syntax of the while loop:

    #include <iostream>
    
    int main() {
        int count = 1;
    
        while (count <= 5) {
            std::cout << "Count: " << count << std::endl;
            count++;
        }
    
        return 0;
    }

    2. Infinite while Loop

    An infinite while loop:

    #include <iostream>
    
    int main() {
        int num = 1;
    
        while (true) {
            std::cout << "Number: " << num << std::endl;
            num++;
            if (num > 5) {
                break; // Exit loop if num exceeds 5
            }
        }
    
        return 0;
    }

    3. Using while Loop with User Input

    Example of using while loop with user input:

    #include <iostream>
    
    int main() {
        int choice;
        std::cout << "Enter a number (0 to exit): ";
        std::cin >> choice;
    
        while (choice != 0) {
            std::cout << "You entered: " << choice << std::endl;
            std::cout << "Enter another number (0 to exit): ";
            std::cin >> choice;
        }
    
        std::cout << "Exiting program." << std::endl;
    
        return 0;
    }

    Conclusion

    The while loop in C++ is versatile and powerful for iterating over a block of code repeatedly based on a specified condition. This chapter covered its basic syntax, infinite loop usage, and how to integrate it with user input scenarios. Mastering while loops allows you to create flexible and responsive programs that handle iterative tasks efficiently.