C++ output upper triangle and lower triangle and diamond and Yang hui triangle of of implementation code

  • 2020-04-02 01:06:57
  • OfStack

1. Output upper triangle
One star in the first row, three in the second row, five in the third row, seven in the fourth row, and nine in the fifth row.
Analysis: The shape of the triangle consists of the output white space and stars. By analyzing the output space and stars in each line, the output triangle can be completed.

#include<iostream>
using namespace std;
int main(){
 int i=0,j=0;
 for(i=1;i<=5;i++){//Control the number of rows
     for(j=1;j<=(5-i);j++){
      cout<<" ";//Control output space
     }
     for(j=1;j<=(2*i-1);j++){
      cout<<"*";//Control output
     }
     cout<<endl;//I'm going to wrap each line
 }
 return 0;
} 

2. Output lower triangle
Nine stars in the first row, seven stars in the second row, five stars in the third row, three stars in the fourth row, and one star in the fifth row.
Analysis: the graph is opposite to the upper triangle graph and the train of thought is similar.

#include<iostream>
using namespace std;
int main(){
 int i=0,j=0;
 for(i=1;i<=5;i++){//Control the number of rows
  for(j=1;j<=(i-1);j++){
   cout<<" ";
  }
  for(j=1;j<=(9-2*(i-1));j++){
   cout<<"*";
  }
  cout<<endl;
 }
} 

3. Output diamond
The rhombus consists of an upper triangle and a lower triangle. You can output it through two for loops

#include<iostream>
using namespace std;
int main(){
 int i=0,j=0;
 for(i=1;i<=5;i++){
  cout<<"t";
  for(j=1;j<=(5-i);j++){
   cout<<" ";
  }
  for(j=1;j<=(2*(i-1)+1);j++){
   cout<<"*";
  }
  cout<<endl;
 }
 for(i=4;i>=1;i--){
  cout<<"t";
  for(j=1;j<=(5-i);j++){
   cout<<" ";
  }
  for(j=1;j<=(2*(i-1)+1);j++){
   cout<<"*";
  }
  cout<<endl;
 }
 cout<<endl;
}

4. Output Yang hui triangle
                  1                                   1   1                               1   2   1                           1   3   3   1                       1   4   6   4   1                   1   5   10   10   5   1               1   6   15   20   15   6   1           1   7   21   35   35   21   7   1       1   8   28   56   70   56   28   8   1   1   9   36   84   126   126   84   36   9   1
The most striking feature of the Yang hui triangle is that each number is equal to the sum of the two Numbers above it. This is how programs are written

#include<iostream>
using namespace std;
int main(){
 int i,j;
 int a[10][21];
 for(i=0;i<10;i++){
  for(j=0;j<21;j++){
   a[i][j]=0;
  }
 }//Completes the initialization of the array
 a[0][10]=1;
    for(i=1;i<10;i++){
     for(j=(10-i);j<=(10+i);j=j+2){//10+i=(10-i)+2*i+01-1
      a[i][j]=a[i-1][j-1]+a[i-1][j+1];
     }
    } 
    for(i=0;i<10;i++){
     cout<<"t"; 
     for(j=0;j<21;j++){
     if(a[i][j]==0){
       cout<<"  "; 
     }else{
      cout<<a[i][j];
     }
     }
     cout<<endl;
    }
    cout<<endl;
}

Related articles: