[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:
- There is NO SPACE at the end of each line.
- There is A NEWLINE (\n) at the end of last line.
That is (.
indicates <space> and ¬
indicates <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: