Diamond pattern C language

describe

Print a diamond pattern formed with "*".

Enter description:

Multiple sets of input, an integer (2~20).

Output description:

For each line of input, the output is a diamond formed by "*" with a space after each "*".

Example 1

Input: 2

output:

  *
 * *
* * *
 * *
  *

Example 2

Input: 3

output:

   *
  * *
 * * *
* * * *
 * * *
  * *
   *

Example 3

enter:

4

output:

    *
   * *
  * * *
 * * * *
* * * * *
 * * * *
  * * *
   * *
    *

Ideas:

        First of all, the two layers of for loops cannot be run away. The outermost for loop is used to control the number of lines, and the inner for loop is used to control spaces and * patterns. We mainly explain the inner for loop.

        When we first get started, it is best to use a pen and paper to draw a picture, which can greatly reduce our thinking burden and difficulty of thinking. Let's deal with the triangle part above.

        To print out the spaces first, print * in each line. As shown in the figure: Through the relationship between a (number of lines) and i (outer for), we can deduce that j = 0; j (inner for)< a - i can satisfy this condition. However, it should be noted that the condition is not unique.

 The pattern is very simple.

  The same is true for the second half. You need to draw a picture to think about it.

The complete code is as follows:        

#include<stdio.h>

int main(void)
{
    int i, j, a = 0;
    while(~scanf("%d", &a))
    {
        for(i = 0; i < a + 1; i++)
        {
            for(j = 0; j < a - i; j++)
            {
                printf(" ");
            }
            for(j = 0; j < i + 1; j++)
            {
                printf("* ");
            }
            printf("\n");
        }
        for(i = 0; i < a ; i++)
        {
            for(j = 0; j <= i; j++)
            {
                printf(" ");
            }
            for(j = 0; j < a - i; j++)
            {
                printf("* ");
            }
            printf("\n");
        }
        
    }
    return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324108191&siteId=291194637