C++ program to print right angled (Right oriented) pyramid of numbers

In this program, we are going to learn how to print numbered pyramids of numbers (which is right angled and right oriented)? This post contains solved program with output and explanation.
Submitted by Abhishek Pathak, on October 10, 2017 [Last updated : February 26, 2023]

Today, we will share a C++ program to print numbered pyramids of numbers. You must be familiar with these types of programs and should try to do it more often, because it will sharpen your skills.

Printing right angled (Right oriented) pyramid of numbers

Here, we are going to implement following pattern:

       1
    2  3
  4 5  6
7 8 9 10

C++ code to print right angled (Right oriented) pyramid of numbers

#include <iostream>
using namespace std;

int main()
{
    int i, j, space, rows, k = 1;

    cout << "Enter the number of rows: ";
    cin >> rows;

    for (i = 1; i <= rows; i++) {
        for (space = i; space < rows; space++) {
            cout << "\t";
        }
        for (j = 1; j <= i; j++) {
            cout << k << "\t";
            k++;
        }
        cout << "\n";
    }

    return 0;
}

Output

RUN 1:
Enter the number of rows: 5
                                1
                        2       3
                4       5       6
        7       8       9       10
11      12      13      14      15

RUN 2:
Enter the number of rows: 3
                1
        2       3
4       5       6

RUN 3:
Enter the number of rows: 7
                                                1
                                        2       3
                                4       5       6
                        7       8       9       10
                11      12      13      14      15
        16      17      18      19      20      21
22      23      24      25      26      27      28

Explanation

We take the number of rows as the limit in the loop. The outer loop is for taking care of rows and the inner loop will take of the columns. In this program we need to take care of the space, as it is important, otherwise pyramid won't form correctly.

Here we initialize the value of space to i, since the number of iterations keep decreasing with the increment of i and that is what we need with successive iterations. Next we run the inner loop upto ith row, since, number of elements in the row is equal to the ith value. In that loop we print the value of k and finally, increment the k for the next iteration. For printing on next row, we print the next line in the end statement of outer loop.

And that's it, nice pattern example, Right? This was the right oriented right angled puzzle. More puzzle like this will be coming soon.

Hope you like the program. Share your thoughts below in the comments.

Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.