Suitable for students to ask some C language topics, this would like to search the Internet, but online methods are divided into the upper and lower parts with two nested for loop output. I think there is no combination of output, so that in line with the requirements of simple and beautiful? The answer is yes.
Analysis:
When the number of rows equals half of the total row number, the ' * ' is incremented and incremented to 2.
When the number of rows is greater than half the total row number, the ' * ' is decremented and incremented to 2.
It has a diamond with a row n,
We use the variable I as the number of rows, starting with 0, I<n.
The number of ' * ' to be exported by K as the first line of N-Ling.
Then the median value of the i<=n (in M, m= (n-1)/2), K increments, and when i>m, K decreases.
Because K is symmetric relative to M line, so:
When I>m, the K value for each increment of i-m is equal to the K value of line m-i, i.e. I-m line and M (i-m) are relative.
So we get the result:
When I<=m, k=2i+1
When I>m, k=2 (M (i-m)) +1, (m= (n-1)/2). namely K=2n-2i-1
Since we only need to output the space on the left of ' * ', the number of spaces to the left of each line ' * ' is: (n per line of K)/2.
Each line loops out the space, then loops out the ' * ' of each line, and then outputs a carriage return, ending a row.
So we can start programming.
-
#include <stdio.h>
int main ()
{
int i,j,k,n;//defines four variables: I is row, J number of spaces before each line *, K the * numbers for each line
printf ("Please input odd n:");
scanf ("%d", &n); //enter odd n
for (i=0;i<n;i++) //loop all rows
{
if (n>=2*i+1) //determine K value
k=2*i+1;
Else
k=2*n-2*i-1;
for (j= (n-k)/2;j>0;j--) //Circular output spaces
printf ("");
for (; k>0;k--) //Circular output * Number
printf ("*");
printf ("n"); //output carriage return end line
}
-
The title is over, but the above procedure is not perfect
For example, what if someone enters an n value for an even number? Enter a non-numeric value?
We add something to go in:
#include <stdio.h>
int main ()
{
int i,j,k,n=0; This gives an initial value to N, even if the input is Non-numeric, n can also have an exact number.
do{ //Add a large loop that allows N to be entered multiple times to observe different results.
printf ("Please input odd N, 0 to exit:")///when entering 0, exit the large loop and end the program.
scanf ("%d", &n);
if (!) ( n%2) //increase the judgment of the input even number.
{
printf ("You are input a even, please input AGAIN.N");
Continue;
}
for (i=0;i<n;i++)
{
if (n>=2*i+1)
K=2*i+1;
Else
K=2*n-2*i-1;
J= (n-k)/2;
for (; j>0;j--)
printf ("");
for (; k>0;k--)
printf ("*");
printf ("n");
}
}while (n);
Return 0;
}