Zhejiang Edition "C Programming Language (3rd Edition)" Title Set Problem 4-9 printed in a diamond pattern (15 minutes)

Here Insert Picture Description
answer:

  • Print graphics must be double loop.
  • Each of the above line stars more gradually, following each row gradually less must be 2 cyclic groups, a top tube, a tube below.
  • Therefore, the weight for the first four lines loop condition i <(n + 1) / 2 above.
  • The first four lines space law: three pairs of first row spaces, the second line of two pairs of spaces, one pair of the third row spaces, no fourth row. 7/2 = 3 and i is from 0 to 3, so think of n / 2 - i.
  • The first four lines Star Law: 1 3 5 7, i from 0 to 3, so think of 2 * i + 1
  • Here and so on.

method one:

#include <stdio.h>
int main()
{
    int n, i, j;
    scanf("%d", &n);
    for (i = 0; i < (n + 1) / 2; i++)
    { //前四行。
        for (j = 0; j < n / 2 - i; j++)
            printf("  ");
        for (j = 0; j < 2 * i + 1; j++)
            printf("* ");
        printf("\n");
    }
    for (i = 1; i <= (n - 1) / 2; i++)
    { //后三行。
        for (j = 0; j < i; j++)
            printf("  ");
        for (j = 0; j < n - 2 * i; j++)
            printf("* ");
        printf("\n");
    }
    return 0;
}

Method Two:

#include <stdio.h>
int main()
{
    int n, i, j;
    scanf("%d", &n);
    for (i = 0; i < n / 2 + 1; i++)
    {
        for (j = 0; j < n / 2 - i; j++)
            printf("  ");
        for (j = 0; j < (i + 1) * 2 - 1; j++)
            printf("* ");
        printf("\n");
    }
    for (i = n / 2; i > 0; i--)
    {
        for (j = n / 2 - i + 1; j > 0; j--)
            printf("  ");
        for (j = i * 2 - 1; j > 0; j--)
            printf("* ");
        printf("\n");
    }
    return 0;
}

For more print other graphics can visit this place

Published 165 original articles · won praise 117 · Views 7801

Guess you like

Origin blog.csdn.net/qq_44458489/article/details/105320749