Two ways to print a diamond in C programming (progressive display)

Keywords: C++ Windows

The first method is to define a space array and a symbol array by using the character array,

Then find the element in the middle of the array, and exchange the space character with the element of the symbol array from the middle to both sides,

Each time the output is exchanged for one time, printing the upper half of diamond and the lower half of diamond requires the support of two for statements.

The source code is as follows:

#include<stdio.h>
#include<stdlib.h>
#Include < windows. H > / / called to use the delay statement Sleep
int main()
{
    char suu1[] = "*****************************************";//Symbolic sentence
    char suu2[] = "                                                         ";//Blank statement
    int right, left=0, mid;
    right = strlen(suu2)-1;
    mid = left + (right - left) / 2;
    for (left = mid , right = mid ; left >= 0&&right<=strlen(suu2)-1 ; left--, right++)//Top half printing
    {
        suu2[left] = suu1[left];
        suu2[right] = suu1[right];
        printf("%s\n", suu2);
        Sleep(600);//Delayed Operation
    }
    for (left = 0, right = strlen(suu1)-1; left <=mid && right >=mid; left++, right--)//Bottom half printing
    {
        suu2[left] = ' ';
        suu2[right] = ' ';
        printf("%s\n", suu2);
        Sleep(600);
    }
    system("pause");
    return 0;
}

This method is simple and easy to understand, but the disadvantage is that the size of the diamond is defined by the length of the defined character array, not particularly flexible.

<2>
Compared with the first method, the second method is more complex in algorithm, but has high maneuverability. It is mainly to get the mathematical relationship between the rows, columns and the number of symbols printed through customs clearance observation to print.

The source code is as follows:

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int line = 0,m,k;
    scanf("%d", &line);//Determine the size of the diamond by entering
    int i = 0;
    for (i = 0; i < line; i++)//Top half printing
    {
        for (m = 0; m<line - 1 - i; m++)//Observed relation
            printf(" ");
        for (m= 0; m <2 * i+ 1; m ++)
        {
                printf("*");
        }
        printf("\n");
    }
    for (i = 0; i < line-1; i++)//Bottom half printing
    {
        for (m = 0; m<=i; m++)
            printf(" ");
        for (m = 0; m <2 * (line-i-1)-1; m++)//Observed relation
        {
            printf("*");
        }
        printf("\n");
    }
    system("pause");
    return 0;
}

Run result instance:

Posted by salasilm on Sun, 01 Dec 2019 03:54:55 -0800