简体   繁体   中英

Simple Triangle/Half Pyramid of natural numbers

I have write following C++ code for display a pyramid of natural numbers

#include <iostream>
using namespace std;
int main()
{
    int i,j,n;
    cout<<"Enter Size:";
    cin>>n;
    for(i=n;i>=1;i--)
    {
    for (j=i;j>0;j--)
    {
        cout<<j;
    }
    cout<<endl;
    
}
 return 0;
}

but if we enter n=3 this code display

321
32
1

I want to display this as

123
12
1

Simply, reverse the second loop.

#include <iostream>
using namespace std;
int main()
{
    int i,j,n;
    cout<<"Enter Size:";
    cin>>n;
    for(i=n;i>=1;i--)
    {
        for (j=1;j<=i;j++) {cout << j << '\t';}
        cout<<endl;
    }
}

Note: the \t tab is simply for aesthetic purpose, as you can see with when the loop gets to number with more than 1 digit:

Enter Size:10
1       2       3       4       5       6       7       8       9       10
1       2       3       4       5       6       7       8       9
1       2       3       4       5       6       7       8
1       2       3       4       5       6       7
1       2       3       4       5       6
1       2       3       4       5
1       2       3       4
1       2       3
1       2
1

Using std::setw() can achieve the same result.

Also, see Why is "using namespace std;" considered bad practice? and The importance of proper indentation

You have to change the j loop, its going from i to 0, and you need to change it to go from 1 to 1 + 1, change it to this and it should work:

for (j=1;j<i+1;j++)

If you want to display like: 123 12 1

Use

    cout<<"Enter Size:";
    cin>>n;
    for(i=1;i<=n;i++)
    {
    for (j=i;j<=n-1;j++)
    {
        cout<<j<<endl;
    }
    cout<<endl;

I your case you display from end to start.

iterate the loops from i to n.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM