-2

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:

Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • Okay: please explain what input you give to your program, what happens, and what you expected to happen instead. – Nate Eldredge Nov 05 '22 at 14:21
  • 1
    `for(j = 1;`: you are reinitializing `j` to 1 every time this for loop begins, so of course the number starts over at 1. You probably want a separate counter variable in place of `j` that you increment every step and don't reinitialize. – Nate Eldredge Nov 05 '22 at 14:23
  • Change `for(j = 1` to `for(j = i`. –  Nov 05 '22 at 14:23

1 Answers1

2

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?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39