While Loops

COS1511 - Introduction To Programming I · Learning C++

While Loops

A while loop is a control structure that allows you to repeat a block of code as long as a specified condition is true. This is useful when you do not know in advance how many times you need to execute the loop. The basic syntax of a while loop in C++ is as follows:

while (condition) {
    // code to be executed
}

Structure of a While Loop

The while loop consists of two main parts: the condition and the body of the loop. The condition is evaluated before each iteration. If the condition is true, the body of the loop is executed. This process repeats until the condition becomes false.

Remember: Ensure that the condition eventually becomes false; otherwise, you will create an infinite loop.

Example of a While Loop

Let’s look at a simple example. Suppose you want to print the numbers from 1 to 5 using a while loop:

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

In this example:

  • The variable i is initialized to 1.
  • The condition checks if i is less than or equal to 5.
  • If true, it prints the value of i and then increments i by 1.

The output will be:

1
2
3
4
5

Infinite Loops

An infinite loop occurs when the condition of the while loop always evaluates to true. This can happen if you forget to update the loop variable or if the condition is always true. For example:

int j = 1;
while (j <= 5) {
    std::cout << j << std::endl;
}

This loop will run indefinitely because the value of j never changes. To avoid infinite loops, always ensure that the loop variable is updated appropriately.

Watch out: Infinite loops can cause your program to freeze. Always test your loop conditions.

Using Break and Continue Statements

You can control the flow of a while loop using the break and continue statements. The break statement exits the loop immediately, while the continue statement skips the current iteration and proceeds to the next iteration.

Example of Break Statement

Here is an example that uses the break statement:

int k = 1;
while (k <= 10) {
    if (k == 6) {
        break;
    }
    std::cout << k << std::endl;
    k++;
}

This code will print numbers from 1 to 5. When k equals 6, the loop will terminate due to the break statement.

Example of Continue Statement

Now, let’s see how the continue statement works:

int m = 1;
while (m <= 5) {
    m++;
    if (m == 3) {
        continue;
    }
    std::cout << m << std::endl;
}

This code will print 2, 4, and 5. When m equals 3, the continue statement skips the current iteration, so 3 is not printed.

Using While Loops for Input Validation

While loops are often used for input validation. For example, you may want to ask a user to enter a positive number:

int number;
std::cout << "Enter a positive number: ";
std::cin >> number;
while (number <= 0) {
    std::cout << "Invalid input. Please enter a positive number: ";
    std::cin >> number;
}

In this example, the loop will continue to prompt the user until they enter a valid positive number.

Nested While Loops

You can also have while loops inside other while loops. This is called a nested while loop. For example, if you want to print a multiplication table:

int row = 1;
while (row <= 5) {
    int col = 1;
    while (col <= 5) {
        std::cout << row * col << " ";
        col++;
    }
    std::cout << std::endl;
    row++;
}

This will produce a 5x5 multiplication table:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Summary

  • A while loop repeats a block of code as long as a condition is true.
  • Be careful to avoid infinite loops by ensuring the loop variable is updated.
  • Use break to exit a loop and continue to skip to the next iteration.
  • While loops are useful for input validation and can be nested.

Check your understanding

  1. What is the purpose of a while loop?
  2. Explain how to avoid an infinite loop.
  3. What happens when you use the continue statement inside a while loop?
  4. Provide an example of using a while loop for input validation.