C++ 程式列印菱形


這是一個用於列印菱形的 C++ 程式。

演算法

Begin
   Take the no of rows n means the dimension of the diamond shape as input.
   Declare the variables i, j and initialize space=1.
   Initialize space = n-1.
   Run for loop till n.
      Run for loop to print space.
      Decrease space.
      Run for loop to print stars.
   Now do the same thing in reverse order.
   Initialize space = 1.
   Run for loop till n.
      Run for loop to print space.
      Increase space.
      Run for loop to print stars.
End

示例

#include<iostream>
using namespace std;
main() {
   int n, i, j, space=1;
   cout<<"Enter number of rows : ";
   cin>>n;
   space=n-1;
   for (i=1; i<=n; i++) {
      for(j=1; j<=space; j++) {
         cout<<" "; //print space.
      }
      space--;
      for(j=1; j<=(2*i-1); j++) {
         cout<<"*"; //print stars.
      }
      cout<<"\n";
   }
   //in reverse order.
   space=1;
   for (i=1; i<=n; i++) {
      for(j=1; j<=space; j++) {
         cout<<" "; //print space.
      }
      space++;
      for(j=1; j<=(2*(n-i)-1); j++) {
         cout<<"*"; //print stars.
      }
      cout<<"\n";
   }
}

輸出

Enter number of rows: 4
*
***
*****
*******
*****
***
*

更新於: 2019 年 7 月 30 日

431 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告