Number Pyramid

Hi all!

I'm trying to make a program that makes a number pyramid that looks like this:


Enter the number of lines: 7
            1
          2 1 2
        3 2 1 2 3
      4 3 2 1 2 3 4
    5 4 3 2 1 2 3 4 5
  6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7


I can not for the life of me figure it out. I think I'm supposed to use 4 for loops to complete it, but I do not know how to set them up.

This is the code I have so far:
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
29
30
31
32
33
34
35
36
#include<iostream>
#include<iomanip>
using namespace std;

int main()
{
	int row;
	cout << "Enter the number of rows: ";
	cin >> row;

	int x = 0;
	int count = row;

	for (int i = 1; i <= row; i++)
	{
		for (int j = 1; j <= row - i; j++)
			cout << " ";

		x = i;

		for (int j = 1; j <= i; j++){
			cout.width(row - j - 1);
			cout << x++;
		}
		x = x - 2;

		for (int j = 1; j < i; j++)
		{
			cout.width(row - j - 1);
			cout << x--;
		}
		cout << endl;
	}

	return 0;
}


Any help would be greatly appreciated!
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
29
30
31
32
33
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;

int main()
{
    int row;
    cout << "Enter the number of rows: ";
    cin >> row;
    
    int x = 0;
    int count = row;
    
    string line = "";
    int length = (row * 2) - 1;
    
    for (int i = 1; i <= row; i++)
    {
        line = "";	    
        for( int j = 1; j <= i; j++ )
            line = " " + to_string(j) + line;
        while( line.size() <= length )
            line = " " + line;
        
        for( int j = 0; j < line.size(); j++ )
            cout << line[j];
        for( int j = line.size() - 2; j >= 0; j-- )
            cout << line[j];
        cout << endl;
    }
    return 0;
}


does not compensate for numbers > 9. I'll let you figure that out :)
Last edited on
Registered users can post here. Sign in or register to post.