Lesson 29 of 60 – while Loop in C++
48%

while Loop in C++

The while loop is used to repeatedly execute a block of code as long as a specified condition is true. It is useful when the number of repetitions is not known in advance.

Note: In a while loop, the condition is checked before every iteration. If the condition is false at the beginning, the loop body does not execute even once.

1. What is a while Loop?

A while loop repeats a block of statements while its condition remains true.

while (condition) {
    // statements
}

When the condition becomes false, the loop stops.

2. Syntax of while Loop

while (condition) {

    // code to repeat

}

The condition is written inside parentheses, and the repeated statements are written inside curly braces.

3. Simple while Loop

int i = 1;

while (i <= 5) {

    std::cout << i << std::endl;

    i++;
}

Output:

1
2
3
4
5

4. Initialization Before while

In a while loop, the loop variable is usually initialized before the while statement.

int i = 1;

while (i <= 5) {
    std::cout << i;
    i++;
}

Here, i starts with the value 1.

5. Condition of while Loop

The condition determines whether the loop body should execute.

int i = 1;

while (i <= 5) {
    std::cout << i;
    i++;
}

The loop continues while i <= 5 is true.

6. Updating the Loop Variable

The loop variable should normally be updated inside the loop. Otherwise, the condition may never become false.

int i = 1;

while (i <= 5) {

    std::cout << i;

    i++;
}

7. How a while Loop Executes

Consider this example:

int i = 1;

while (i <= 3) {

    std::cout << i;

    i++;
}
  1. i starts with 1.
  2. The condition i <= 3 is checked.
  3. The loop body executes.
  4. i++ increases the value.
  5. The condition is checked again.
  6. The process continues until the condition becomes false.

8. Printing Numbers from 1 to 10

int i = 1;

while (i <= 10) {

    std::cout << i << std::endl;

    i++;
}

This prints numbers from 1 through 10.

9. Printing Numbers from 10 to 1

int i = 10;

while (i >= 1) {

    std::cout << i << std::endl;

    i--;
}

The loop counts backward from 10 to 1.

10. Printing Even Numbers

int i = 2;

while (i <= 20) {

    std::cout << i << std::endl;

    i += 2;
}

The value increases by 2, so only even numbers are printed.

11. Printing Odd Numbers

int i = 1;

while (i <= 19) {

    std::cout << i << std::endl;

    i += 2;
}

12. while Loop with User Input

#include <iostream>

int main() {

    int n;

    std::cout << "Enter a number: ";
    std::cin >> n;

    int i = 1;

    while (i <= n) {

        std::cout << i << std::endl;

        i++;
    }

    return 0;
}

The number of iterations depends on the value entered by the user.

13. while Loop with if Statement

An if statement can be placed inside a while loop.

int i = 1;

while (i <= 10) {

    if (i % 2 == 0) {
        std::cout << i << std::endl;
    }

    i++;
}

This program prints the even numbers from 1 to 10.

14. Sum of Numbers Using while

int i = 1;
int sum = 0;

while (i <= 10) {

    sum += i;

    i++;
}

std::cout << "Sum = " << sum;

The program adds all numbers from 1 to 10.

15. Multiplication Table

int number = 5;
int i = 1;

while (i <= 10) {

    std::cout << number
              << " x "
              << i
              << " = "
              << number * i
              << std::endl;

    i++;
}

This program prints the multiplication table of 5.

16. Factorial Using while Loop

int number = 5;
int factorial = 1;
int i = 1;

while (i <= number) {

    factorial *= i;

    i++;
}

std::cout << "Factorial = "
          << factorial;

The factorial of 5 is 120.

17. Reading Input Until a Condition

A while loop is useful when the number of iterations is not known in advance.

int number;

std::cout << "Enter a positive number: ";
std::cin >> number;

while (number <= 0) {

    std::cout << "Enter again: ";
    std::cin >> number;
}

std::cout << "Valid number entered";

The loop continues until the user enters a positive number.

18. while Loop for Password Attempts

#include <iostream>
#include <string>

int main() {

    std::string password;

    std::cout << "Enter password: ";
    std::cin >> password;

    while (password != "1234") {

        std::cout << "Wrong password. Try again: ";
        std::cin >> password;
    }

    std::cout << "Correct password";

    return 0;
}

The loop continues until the correct password is entered.

19. Using break in while Loop

The break statement immediately terminates a while loop.

int i = 1;

while (i <= 10) {

    if (i == 5) {
        break;
    }

    std::cout << i << std::endl;

    i++;
}

The loop stops when i becomes 5.

20. Using continue in while Loop

The continue statement skips the remaining statements of the current iteration and moves to the next iteration.

int i = 0;

while (i < 5) {

    i++;

    if (i == 3) {
        continue;
    }

    std::cout << i << std::endl;
}

The number 3 is skipped.

21. Infinite while Loop

An infinite loop is a loop whose condition never becomes false.

int i = 1;

while (i <= 5) {

    std::cout << i;

    // i is never updated
}

This loop keeps running because i remains 1. Always make sure the loop can eventually reach a false condition, unless an intentional infinite loop is required.

22. while Loop with Array

int numbers[] = {10, 20, 30, 40, 50};

int i = 0;

while (i < 5) {

    std::cout << numbers[i]
              << std::endl;

    i++;
}

The loop accesses each array element using its index.

23. while Loop with String

#include <iostream>
#include <string>

int main() {

    std::string name = "SOOPRO";

    int i = 0;

    while (i < name.length()) {

        std::cout << name[i]
                  << std::endl;

        i++;
    }

    return 0;
}

The loop prints each character of the string.

24. Menu Using while Loop

#include <iostream>

int main() {

    int choice = 0;

    while (choice != 4) {

        std::cout << "1. Add" << std::endl;
        std::cout << "2. View" << std::endl;
        std::cout << "3. Delete" << std::endl;
        std::cout << "4. Exit" << std::endl;

        std::cout << "Enter choice: ";
        std::cin >> choice;

        if (choice == 1) {
            std::cout << "Add selected" << std::endl;
        }
        else if (choice == 2) {
            std::cout << "View selected" << std::endl;
        }
        else if (choice == 3) {
            std::cout << "Delete selected" << std::endl;
        }
        else if (choice != 4) {
            std::cout << "Invalid choice" << std::endl;
        }
    }

    return 0;
}

25. Nested while Loop

A while loop can be placed inside another while loop.

int i = 1;

while (i <= 3) {

    int j = 1;

    while (j <= 3) {

        std::cout << i
                  << ","
                  << j
                  << std::endl;

        j++;
    }

    i++;
}

26. while Loop vs for Loop

Both loops can repeat code, but their common uses are slightly different.

for Loop while Loop
Often used when the number of iterations is known. Often used when the stopping condition is more important than a fixed count.
Initialization, condition, and update appear together. Initialization and update are usually written separately.
Compact for counter-based loops. Useful for input validation and condition-controlled repetition.

27. Complete Number Analysis Program

#include <iostream>

int main() {

    int n;

    std::cout << "Enter a number: ";
    std::cin >> n;

    int i = 1;

    while (i <= n) {

        if (i % 2 == 0) {

            std::cout << i
                      << " is even"
                      << std::endl;

        }
        else {

            std::cout << i
                      << " is odd"
                      << std::endl;

        }

        i++;
    }

    return 0;
}

28. Practical ATM Example

#include <iostream>

int main() {

    int choice = 0;

    while (choice != 3) {

        std::cout << "1. Check Balance"
                  << std::endl;

        std::cout << "2. Deposit"
                  << std::endl;

        std::cout << "3. Exit"
                  << std::endl;

        std::cout << "Enter choice: ";
        std::cin >> choice;

        switch (choice) {

            case 1:
                std::cout << "Balance selected"
                          << std::endl;
                break;

            case 2:
                std::cout << "Deposit selected"
                          << std::endl;
                break;

            case 3:
                std::cout << "Exiting..."
                          << std::endl;
                break;

            default:
                std::cout << "Invalid choice"
                          << std::endl;
        }
    }

    return 0;
}

29. Common while Loop Mistakes

  • Forgetting to initialize the loop variable.
  • Forgetting to update the loop variable.
  • Writing a condition that is always true.
  • Using the wrong comparison operator.
  • Creating an accidental infinite loop.
  • Forgetting that the condition is checked before the loop body.
  • Using continue without making sure the loop variable is still updated.
  • Accessing an array outside its valid index range.

Correct example:

int i = 1;

while (i <= 5) {

    std::cout << i;

    i++;
}

30. while Loop – Final Summary

Part Purpose
Initialization Sets the starting value before the loop.
Condition Determines whether the loop continues.
Loop Body Contains the statements that are repeated.
Update Changes the loop variable so the loop can eventually stop.
break Immediately terminates the loop.
continue Skips the current iteration.
int i = 1;

while (i <= 10) {

    std::cout << i;

    i++;
}

📌 Key Points

  • The while loop repeats code while a condition is true.
  • The condition is checked before every iteration.
  • If the condition is false initially, the loop does not execute.
  • The loop variable should usually be updated inside the loop.
  • Forgetting the update can create an infinite loop.
  • break can terminate the loop immediately.
  • continue skips the current iteration.
  • while loops are useful when the number of repetitions is not known in advance.
  • A while loop can contain if statements and other loops.
  • Always make sure the loop has a valid stopping condition.

🧠 Quick Quiz

Question: When is the condition of a while loop checked?