创建列和行;询问用户想要输出的行数然后显示

时间:2013-10-15 16:57:57

标签: c++ rows multiple-columns

//libraries
#include <iostream>

//global constants

//no functioning prototypes
using namespace std;

int main(){
    //Define variables
    int n; // Number of rows
    int i; // Row count in for loop
    int k; // Output for loop

    // Have user input n
    cout << "Enter number of rows: ";
    cin >> n;

    // Complete for loop
    for (i = 1; i <= n + 1; i++){
    for (k = 1; k < i; k++){
    cout << k%10;
}
  cout << endl;
}

    system("PAUSE");
    return EXIT_SUCCESS;
}

我正在尝试创建一个与此类似的代码,而不是放置

1
12
123
1234
12345

我需要它看起来像

1
 2
  3
   4
    5

其中结尾编号是列数是输入的数字和空格而不是之前的数字

2 个答案:

答案 0 :(得分:1)

您只需要替换此行:

cout << k%10;

这一行:

if (k<i-1) cout << ' '; else cout << k%10;

如果我们在当前行的最后位置,则打印数字;如果不是,则打印空格。

答案 1 :(得分:0)

#include "stdafx.h"
#include"iostream"
#include"conio.h"
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
int a=1;
int n;
cout<<"enter the lenght of the numbers";
cin>>n;

for (int i=1;i<=n;i++)
{
    {for (int j=1;j<=n;j++)
        if (j==a)
            cout<<j;
        else cout<<" ";
    }
    cout<<endl;
    a=a+1;
}

_getch();   
}