c++中的Floyd模式

Floyd pattern in c++

本文关键字:模式 Floyd 中的 c++      更新时间:2023-10-16

嗨,我试着在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

如何打印余额输出。但是我怎样才能打印出这个图案的镜像呢?

首先,上面的代码是错误的,它应该是:

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;
}

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;
}