[Loops]D. Liang 4.18 Printing four patterns using loop
Description
Write a program that reads two intergers p(1<=p<=4) and n(3<=n<=10), then display one of the following patterns.
For example, when n = 6, the outputs are as follow:
Pattern 1
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
Pattern 2
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Pattern 3
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
Pattern 4
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Input
two integers, p (1<=p<=4) and n (3<=n<=10).
Output
Pattern p.
You should specify the width of each number’s print field to 3, justify the output to right.
There is no extra space at the end of a line.
Sample Input
1 6
Sample Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
Analysis: because there are four situations, we can consider calling four different functions to solve this problem. The correct code is as follows:
// Date:2020/3/19
// Author:xiezhg5
#include<stdio.h>
//打印第一种情形
void print1(int n)
{
int i,j;
//i控制行数
//j打印数字
for(i=1;i<=n;i++)
{
//根据i的变化输出数字个数
for(j=1;j<=i;j++)
printf("%3d",j);
printf("\n"); //不要忘记换行
}
}
//打印第二张情形
//与第一种情形类似(逆序输出)
void print2(int n)
{
int i,j;
for(i=n;i>=1;i--)
{
for(j=1;j<=i;j++)
printf("%3d",j);
printf("\n");
}
}
//打印第三种情形
//与第一种情形相比多了打印空格这一步骤
void print3(int n)
{
int i,j,k;
for(i=1;i<=n;i++)
{
for(k=1;k<=n-i;k++) //空格数与行数间的关系(n-i)
printf(" "); //每个数字占三位故打印三个空格
for(j=1;j<=n-k+1;j++) //每行数字的个数与行数和空格数的关系(n-k+1)
printf("%3d",j);
printf("\n");
}
}
//打印第四种情形
//与第三种情形类似
void print4(int n)
{
int i,j,k;
for(i=n;i>=1;i--)
{
for(k=1;k<=n-i;k++)
printf(" ");
for(j=1;j<=n-k+1;j++)
printf("%3d",j);
printf("\n");
}
}
int main(void)
{
int m,n;
scanf("%d %d",&m,&n);
//有四种不同情况可用switch语句
switch(m)
{
case 1:print1(n);break;
case 2:print2(n);break;
case 3:print3(n);break;
case 4:print4(n);break;
}
return 0;
}
***Running screenshot:***
99 points (little code):
// Date:2020/3/19
// Author:xiezhg5
#include <stdio.h>
int main(void)
{
int p,n,cnt=1,i=0,a=1,c;
scanf("%d %d",&p,&n);
if(p==2||p==4) cnt=n;
for(;cnt<=n&&cnt>0;i=0,a=1,cnt--)
{
if(p==3||p==4)
for(c=n-cnt;c>0;c--)
{
printf(" ");
}
for(i=0;i<cnt;i++,a++)
printf("%3d",a);
printf("\n");
if(p==1||p==3) cnt=cnt+2;
}
return 0;
}
98 points:
#include<stdio.h>
int main(void)
{
int i,j,k;
int m,n;
scanf("%d %d",&m,&n);
if(m==1){
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
printf("%3d",j);
printf("\n");
}}
if(m==2){
for(i=n;i>=1;i--)
{
for(j=1;j<=i;j++)
printf("%3d",j);
printf("\n");
}}
if(m==3) {
for(i=1;i<=n;i++)
{
for(k=1;k<=n-i;k++)
printf(" ");
for(j=1;j<=n-k+1;j++)
printf("%3d",j);
printf("\n");
}}
if(m==4){
for(i=n;i>=1;i--)
{
for(k=1;k<=n-i;k++)
printf(" ");
for(j=1;j<=n-k+1;j++)
printf("%3d",j);
printf("\n");
}}
return 0;
}