[Loops]D. Liang 4.19 Printing numbers in a pyramid pattern.c

[Loops]D. Liang 4.19 Printing numbers in a pyramid pattern

Description

Write a program that reads an interger n, then display the n levels pyramid pattern.
For example, if n=4, the pattern is as follow:

                   1
              1    2    1
         1    2    4    2    1
    1    2    4    8    4    2    1

Input

An integer n (1<=n<=8).

Output

The n levels Pattern.
You should specify the width of each number’s print field to 5, justify the output to right.

NOTE:

  1. There is NO SPACE at the end of each line.
  2. There is A NEWLINE (\n) at the end of last line.

That is (. indicates <space> and ¬ indicates &lt;newline>)

..........1¬
.....1....2....1¬

Sample Input

4

Sample Output

                   1
              1    2    1
         1    2    4    2    1
    1    2    4    8    4    2    1

Analysis: the middle number is the (i-1) power of 2, I is the number of lines, which is symmetrical distribution, so it needs to use two cycles; printing space needs to use cycles; using I to control the number of lines also needs to use cycles.
The code is as follows:

//   Date:2020/3/19
//   Author:xiezhg5
#include <stdio.h>
#include <math.h>
void main()
{
  int n;
  int i,j,k,b,a;
  scanf("%d",&n);
  for(i=1;i<=n;i++)     //i控制行数 
  {   
	  for(j=n;j>i;j--)  //j随i的变化输出空格 
	  {
		printf("     ");//数字占5位故需用5个空格 
	  }
	  for(k=1;k<=(2*i+1)/2;k++) //打印最中间一个数 
	  {
	  	b=pow(2,k-1);
		printf("%5d",b);
	  }
	  for(k=(2*i+1)/2;k>=1;k--) //打印中间的两边的数(逆序) 
	  {
	  	a=pow(2,k-2);
	  	if(a!=0)      //当a为0时不输出 
	    printf("%5d",a);
	  }
	  printf("\n");
  }
}

Running screenshot:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值