在 C++ 中列印反向鑽石圖案的程式


在本教程中,我們將討論一個程式以列印給定的反向鑽石圖案。

為此,我們將獲得 N 值。我們的任務是根據 2N-1 的高度列印反向鑽石圖案。

示例

 動態演示

#include<bits/stdc++.h>
using namespace std;
//printing the inverse diamond pattern
void printDiamond(int n){
   cout<<endl;
   int i, j = 0;
   //loop for the upper half
   for (i = 0; i < n; i++) {
      //left triangle
      for (j = i; j < n; j++)
         cout<<"*";
      //middle triangle
      for (j = 0; j < 2 * i + 1; j++)
         cout<<" ";
      //right triangle
      for (j = i; j < n; j++)
         cout<<"*";
      cout<<endl;
   }
   //loop for the lower half
   for (i = 0; i < n - 1; i++) {
      //left triangle
      for (j = 0; j < i + 2; j++)
         cout<<"*";
      //middle triangle
      for (j = 0; j < 2 * (n - 1 - i) - 1; j++)
         cout<<" ";
      //right triangle
      for (j = 0; j < i + 2; j++)
         cout<<"*";
      cout<<endl;
   }
   cout<<endl;
}
int main(){
   int n = 5;
   printDiamond(n);
   return 0;
}

輸出

 ***** *****
****     ****
***       ***
**          **
*             *
**          **
***       ***
 ****    ****
 ***** *****

更新時間: 02-Jan-2020

310 次瀏覽

開啟您的 職業 之路

完成課程進行認證

開始
廣告