嗨,我尝试在c ++中打印以下模式
1
2 3
4 5 6
7 8 9 10
7 8 9 10
4 5 6
2 3
1
使用以下循环打印一半。
int i,j,k=1;
cout<<"Enter row";
cin>>n;
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
cout<<k<<"\t";
k++;
}
}
我得到了像
这样的输出1
2 3
4 5 6
7 8 9 10
如何打印平衡输出。但我怎样才能打印出这种模式的镜子。
答案 0 :(得分:-1)
首先,上面的代码是错误的,它应该是:
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
cout<<k<< " ";
k++;
}
cout << '\n';
}
现在,要绘制模式,您可以使用一个使用以下逻辑的循环:
for(;i > 0; i--)
{
k -= i-1;
for(j=1;j<i;j++)
{
cout <<k<< " ";
k++;
}
cout << '\n';
k -= i-1;
}
答案 1 :(得分:-1)
int main()
{
int n;
int i, j, k = 1;
cout << "Enter row";
cin >> n;
int elemcount = 0;
for (i = 1; i <= n; i++)
{
elemcount = 0;
for (j = 1; j <= i; j++)
{
cout << k << "\t";
k++;
}
cout <<endl;
}
k = k - n; //Reset Counter to the value of the first digit in current row.
i--;
j--;
for (; i > 0; i--)
{
j = i;
elemcount = 0; //Counter to keep track of elements printed.
for (; j> 0; j--)
{
cout << k << "\t";
k++;
elemcount++;
}
k = k - elemcount - (i-1); //Resetting K, substracting the number of elements printed and number of elements to be printed in next row.
cout << endl;
}
return 0;
}