Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write a C++ program which will print (half pyramid) pattern of natural numbers

The task:
Write a C++ program which will print (half pyramid) pattern of natural numbers.

1
2  3
4  5  6
7  8  9  10
11 12 13 14 15

I have tried using this code, but its not giving the output:

#include <iostream>
using namespace std;
int main()
{
    int rows, i, j;
    cout << "Enter number of rows: ";
    cin >> rows;
    for(i = 1; i <= rows; i++)
    {
        for(j = 1; j <= i; j++)
        {
            cout << j << " ";
        }
        cout << "\n";
    }
    return 0;
}

OUTPUT:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

>Solution :

j in your inner loop is the 1 based index of the element in the current row (1,2,3 etc.).
Instead of printing it, you should print a counter that is increased over all the iterations.

Something like:

#include <iostream>

int main()
{
    int rows, i, j;
    std::cout << "Enter number of rows: ";
    std::cin >> rows;
    int n = 1;
    for (i = 1; i <= rows; i++)
    {
        for (j = 1; j <= i; j++)
        {
            std::cout << n << " ";
            n++;  // for next iteration
        }
        std::cout << "\n";
    }
    return 0;
}

Output example:

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

A side note: better to avoid using namespace std – see here Why is "using namespace std;" considered bad practice?.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading