2020-9-13 Output diamond pattern

Output diamond pattern

Topic : Write a program to output a diamond pattern. The first line is a letter A, the second line is three letters B, and so on, the nth line is 2n-1 corresponding letters, and each line is decremented. There is keyboard input for n.
Feeling : The key is to use the for loop to control the number of spaces and letters in each line.
Key : The most critical place is the value and range of the loop variable in the for loop.
In fact, it is also the knowledge of the simplest mathematical sequence.
Let’s take the input n=5 as an example.
Because we want to output a diamond pattern, we need to use a sequence of numbers 5 , 4, 3, 2, 1, 2, 3
when controlling the input of each line of spaces. , 4, 5;
how to construct it? k=1-n; the value sequence of k is -4,-3,-2,-1,0,1,2,3,4; the value of k is actually meaningless, the purpose is to construct the next sequence
i=n-abs(k); At this time, the value sequence of i is constructed. 1, 2, 3, 4, 5, 4, 3, 2, 1
are compared when controlling the input of the number of letters in each row Simple, you can find that the number of letters in each row is an arithmetic sequence: 1, 3, 5, 7, 9, 7, 5, 3, 1; at this time, the value range of j only needs to be 2*i- 1 can
code :
/*09 : 01 : 36 on September 13, 2020
output diamond pattern (simple version)
/
#include<stdio.h>
#include<math.h>
int main()
{ char c; int i ,j,k,n;


printf("Enter n:");
scanf("%d",&n);
printf("corresponding diamond pattern\n");
c='A';
for(k=1-n;k<=n- 1;k++)// Taking n as 5 as an example, demonstrate that each variable takes the value k:-4,-3,-2,-1,0,1,2,3,4
{i=n-abs(k ); // i:1,2,3,4,5,4,3,2,1
for(j=1;j<=n-i+1;j++)// j:5,4,3, The number of blank lines per line represented by 2,1,2,3,4,5
printf(" ");
for(j=1;j<=2
i-1;j++)//There is also a trick j here: 1,3,5,7,9,7,5,3,1
printf("%c",c);
printf("\n");
c++;
}
return 0;
}The output result when n is 5

Guess you like

Origin blog.csdn.net/brucecui1998/article/details/108560025