Print a Pattern of Numbers in C++

In this exercise, you will create a C++ program that prints a pattern of numbers from 1 to a specified number. The program will prompt the user to input the number up to which they want the pattern to print. Then, it will print the numbers starting from 1 and continuing incrementally up to the specified number in the same row.

This exercise helps reinforce the understanding of loops and output formatting in C++. It also demonstrates how to work with user input and print patterns using basic loops.

Group

Flow Control in C++

Objective

1. Prompt the user to input the maximum number up to which the pattern should print.
2. Use a loop to print numbers starting from 1 and continue up to the maximum number.
3. Ensure that all numbers are printed in a single row, separated by spaces.
4. Display the pattern on the screen.

Write a program that prints a pattern of numbers (1, 2, 3, 4...).

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output

using namespace std; // Use the standard namespace

// Main function - entry point of the program
int main() {
    int n; // Variable to store the maximum number

    // Prompt the user to enter the maximum number for the pattern
    cout << "Enter the maximum number for the pattern: ";
    cin >> n; // Read the input number

    // Loop to print numbers from 1 to the specified number
    for (int i = 1; i <= n; i++) { // Start from 1 and print numbers up to n
        cout << i << " "; // Print the current number followed by a space
    }

    cout << endl; // Move to the next line after printing the pattern

    return 0; // Return 0 to indicate successful execution of the program
}

 Output

Enter the maximum number for the pattern: 10
1 2 3 4 5 6 7 8 9 10

//Or for another input:
Enter the maximum number for the pattern: 5
1 2 3 4 5

Share this C++ Exercise


More C++ Programming Exercises of Flow Control in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.