C学习之路-使用C打印金字塔

#include <stdio.h>

//for循环
func1(int height){
   int width=1;
   int height_temp=1;
  for(;height_temp<=height;height_temp++){
    for(width;width<=(height-height_temp);width++){
      printf(" ");
     }
     width=1;
    for(width;width<=(height_temp*2-1);width++){
     printf("*");
     }
     width=1;
    printf("\n");
  
  }
}
//while循环
func2(int height){
  int width=1;
  int height_temp=1;
  while(height_temp<=height){
    while(width<=(height-height_temp)){
      printf(" ");
      width++;
     };
     width=1;
    while(width<=(height_temp*2-1)){
      printf("*");
      width++;
     };
     width=1;
     printf("\n");
     height_temp++;
  }
}

//do_while循环
func3(int height){
  int height_temp=1;
  int sum = height;
  do{
    int space =  (sum-height_temp);
    do{
	  if(space<=0)break;
      printf(" ");
    }while(space-=1);

     int star = 0;
     star=(height_temp*2)-1;

	 do{
	  if(star<=0)break;
	  printf("*");
	 }while(star-=1);

	 height_temp++;
    printf("\n");
  }while(height-=1);
}

//打印横向*
func5_1(int width){
  if(width<=0)return;
  printf("*");
  func5_1(width-=1);
}
//打印空格
func5_2(int space){
  if(space<=0)return;
  printf(" ");
  func5_2(space-=1);
}

//递归
func5(int height,int sum){
  if(height<=0)return;
  func5(height-=1,sum);
  int star = height+1;
  func5_2(sum-star);
  func5_1(star*2-1);
  printf("\n");
}




int main(){

    printf("请输入你需要建造的金字塔层数:");
    int height;
    scanf("%d",&height);
	func1(height);
	func2(height);
    func3(height);
    func5(height,height);
}

猜你喜欢

转载自blog.csdn.net/qq2523208472/article/details/84073867