-2

This is the code I tried but I need a pattern like this:

1 2 3 4
  2 3 4
    3 4
      4

Please help me with the code.

#include <iostream>
using namespace std;

int main()
{
    int rows;

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

    for(int i = rows; i >= 1; --i)
    {
        for(int j = 1; j <= i; ++j)
        {
            cout << j << " ";
        }
        cout << endl;
    }

    return 0;
}

The code currently prints:

1 2 3 4 
1 2 3 
1 2 
1 
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60

3 Answers3

1

You need to use increasing loops:

for(int i = 1; i <= rows; i++) {
    for(int j = 1; j <= rows; j++) {
        if(j < i) {
            cout << "  ";
        } else {
            cout << j << " ";
        }
    }
    cout << endl;
}
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
1

You must include <iomanip>

for (int i = 1; i <= row; i++)
{
    cout << setw(i * 2 - 1);
    for (int j = i; j <= row; j++)
    {
        cout << j << " ";
    }
    cout << endl;
}
secuman
  • 539
  • 4
  • 12
0

we should know that the space of each line from left increases frequently.you did not choose loops start and end correctly.outer loop must start from 1 to rows and inner loop must start from index of outer loop to rows.as we see the space of each line increases and first line has no space , so we define a variable named 'k' to hold sapces count and each time we increase it by step 2.

enter image description here

#include <iostream>
using namespace std;
//by Salar Ashgi
void space(int n)
{
    for(int i=1;i<=n;i++)
    cout<<" ";
}
int main()
{
    int rows;
    cout<<"Enter number of rows>> ";
    cin>>rows;
    int k=0;
    for(int i=1;i<=rows;i++)
    {
        space(k);
        for(int j=i;j<=rows;j++)
        {
            cout<<j<<" ";
        }
        cout<<endl;
        k+=2;
    }
}
Salar Ashgi
  • 128
  • 2
  • 13