Number Pattern Exercise | Loops and Output Formatting

Print a Pattern of Numbers in C++

In this exercise, you will create a C++ program that prints a sequence of numbers from 1 to a user-defined limit. This task is essential for mastering how loops control program execution and how to format console output in a single row.

Logic Components

1. Loop Initialization

Setting the starting point at i = 1 ensures the pattern begins correctly as requested by the exercise.

2. Loop Condition

Using i <= n allows the loop to include the final number entered by the user in the output.

3. Inline Output

By avoiding endl inside the loop, we keep all numbers in a single horizontal row separated by spaces.

Objective

  • 1. Prompt the user for a maximum integer limit.
  • 2. Implement a for loop that iterates from 1 to the given number.
  • 3. Print each number followed by a space in the same line.
  • 4. Close the output with a single new line for clean console display.

Example C++ Exercise

number_pattern.cpp Flow Control
#include <iostream> // Include library for input/output

using namespace std; // Use standard namespace

int main() {
    int n; // Variable to store the limit

    // Ask the user for the limit
    cout << "Enter the maximum number for the pattern: ";
    cin >> n; 

    // Loop to print the sequence
    for (int i = 1; i <= n; i++) { 
        // Print current value of 'i' and a space
        cout << i << " "; 
    }

    // Clean finish with a new line
    cout << endl;

    return 0; // End of program
}

Console Output:

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

// Example with a different input:
Enter the maximum number for the pattern: 5
1 2 3 4 5
Flow Control & Logic
Basic For Loops Sequential Patterns C++ I/O Formatting Introductory Logic

Share this C++ Exercise

Help others master basic loops and patterns in C++.

© C++ Programming Exercises. Build your logic, brick by brick.