Start learning free

LESSON 118 OF 409 · WHILE LOOPS & FOR LOOPS

While loop: Printing more numbers in C++ in C++

Lesson Read the full explanation

Practice makes perfect! Let's check two more examples of printing numbers using the while loop.


Example 1:

Let's print all the even numbers from 4 through 14:

int i = 4;
while(i <= 14) {
	cout << i << endl;
	i += 2;
}

The output of this program is:

4
6
8
10
12
14

Example 2:

We can also loop in reverse. Let's print all even numbers from 12 to 4 in decreasing order:

int i = 12;
while(i >= 4) {
	cout << i << endl;
	i -= 2;
}

The output of this program is:

12
10
8
6
4

Assignment
Let's print all the odd numbers from 23 to 7 in decreasing order!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    C++ · WHILE LOOPS & FOR LOOPS

    Printing Numbers 2 in C++, explained

    Introduction

    In this lesson, we will explore the use of the while loop in C++ to print sequences of numbers. The while loop is a fundamental control structure that allows code to be executed repeatedly based on a given condition. Understanding how to use loops effectively is crucial for solving many programming problems, such as iterating over data structures, performing repetitive tasks, and implementing algorithms.

    Understanding the Basics

    The while loop in C++ repeatedly executes a block of code as long as a specified condition is true. The syntax of a while loop is as follows:

    while (condition) {
        // Code to execute
    }
    

    It's important to ensure that the condition will eventually become false; otherwise, the loop will run indefinitely, causing an infinite loop.

    Main Concepts

    Let's break down the key concepts and techniques involved in using the while loop:

    • Initialization: Set up an initial value for the loop control variable.
    • Condition: Specify the condition that must be true for the loop to continue executing.
    • Update: Modify the loop control variable within the loop to eventually make the condition false.

    By following these steps, you can control the flow of the loop and ensure it executes the desired number of times.

    Examples and Use Cases

    Let's look at some examples to illustrate the use of the while loop:

    Example 1: Printing Even Numbers from 4 to 14

    int i = 4;
    while (i <= 14) {
        cout << i << endl;
        i += 2; // Increment by 2 to get the next even number
    }
    

    This loop starts with i set to 4 and increments by 2 each time, printing even numbers until i exceeds 14.

    Example 2: Printing Even Numbers from 12 to 4 in Reverse

    int i = 12;
    while (i >= 4) {
        cout << i << endl;
        i -= 2; // Decrement by 2 to get the previous even number
    }
    

    This loop starts with i set to 12 and decrements by 2 each time, printing even numbers in reverse order until i is less than 4.

    Assignment: Printing Odd Numbers from 23 to 7 in Decreasing Order

    int i = 23;
    while (i >= 7) {
        cout << i << endl;
        i -= 2; // Decrement by 2 to get the previous odd number
    }
    

    This loop starts with i set to 23 and decrements by 2 each time, printing odd numbers in decreasing order until i is less than 7.

    Common Pitfalls and Best Practices

    When using while loops, be mindful of the following common pitfalls:

    • Infinite Loops: Ensure the loop condition will eventually become false to avoid infinite loops.
    • Off-by-One Errors: Carefully set the initial value and update the loop control variable to avoid missing or repeating iterations.

    Best practices for writing clear and maintainable while loops include:

    • Clearly comment the purpose of the loop and the logic behind the condition and updates.
    • Use meaningful variable names to make the code more readable.
    • Keep the loop body concise and focused on a single task.

    Advanced Techniques

    Once you are comfortable with basic while loops, you can explore more advanced techniques such as nested loops, combining loops with other control structures, and using loops for complex data processing tasks.

    Code Implementation

    Here is the complete code for the assignment:

    #include <iostream>
    using namespace std;
    
    int main() {
        int i = 23;
        while (i >= 7) {
            cout << i << endl;
            i -= 2; // Decrement by 2 to get the previous odd number
        }
        return 0;
    }
    

    This code demonstrates how to use a while loop to print odd numbers from 23 to 7 in decreasing order.

    Debugging and Testing

    When debugging while loops, consider the following tips:

    • Use print statements to track the value of the loop control variable at each iteration.
    • Check the loop condition and ensure it will eventually become false.
    • Test the loop with different initial values and conditions to ensure it behaves as expected.

    Writing test cases for functions that use loops can help verify their correctness. For example, you can write tests to check the output of the loop for different ranges of numbers.

    Thinking and Problem-Solving Tips

    When approaching problems that involve loops, consider the following strategies:

    • Break down the problem into smaller steps and solve each step incrementally.
    • Use pseudocode to outline the logic before writing the actual code.
    • Practice solving similar problems to build confidence and improve your skills.

    Conclusion

    In this lesson, we explored the use of the while loop in C++ to print sequences of numbers. We covered the basics of loop initialization, condition, and updates, and provided examples to illustrate these concepts. By mastering the use of loops, you can solve a wide range of programming problems efficiently.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free