C++ Program to Print Number Pattern without Reassigning

27/04/2024 0 By indiafreenotes

Printing a number pattern in C++ often involves creating nested loops. A common challenge or limitation for some tasks might be not to reassign variables within the loops.

  • Example: Ascending Number Pattern

Let’s create a simple program that prints an ascending number pattern, where each row starts from 1 and goes up to the number equal to the row number.

C++ Code:

 

#include <iostream>

using namespace std;

int main() {

    int rows;

    // User inputs the number of rows for the pattern

    cout << “Enter the number of rows: “;

    cin >> rows;

    // Print the number pattern

    for (int i = 1; i <= rows; ++i) {  // Outer loop for each row

        for (int j = 1; j <= i; ++j) { // Inner loop for each number in the row

            cout << j << ” “;  // Print each number followed by a space

        }

        cout << endl;  // Move to the next line after each row is complete

    }

    return 0;

}

 

Explanation:

  • Header and Namespace:

The program includes the <iostream> header for input/output operations and uses the std namespace.

  • Input:

The program prompts the user to enter the number of rows for the pattern. This determines how tall the pattern will be.

  • Outer Loop:

This loop controls the rows of the pattern. It runs from 1 to rows. The variable i indicates the current row number and is used to determine how many numbers to print on that row.

  • Inner Loop:

Inside each row, this loop prints numbers starting from 1 up to the row number (i). The variable j represents the current number being printed.

  • Output:

Each number is followed by a space (cout << j << ” “;), and each row ends with a newline (cout << endl;).

Program Output:

If the user enters 5 for the number of rows, the output will be:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

This program achieves the task of printing a simple number pattern without reassigning any variables within the loop bodies, sticking to the initial assignments. Each variable in the loops (i and j) is assigned only once per loop cycle and used consistently within its scope. This pattern is scalable and can be adjusted or expanded to include different sequences or formats by modifying the initial values and conditions of the loops.