标签归档:菱形

C语言输出菱形图像

使用C语言输出如下图像

思路:确定每行开始位置,和该行’*’的总个数。
代码文件,该图形可以整体右移,请调节 #define LEFT 1 参数

[lhf@localhost work]$ cat diamond.c
/**
 *     *
 *    * *
 *   * * *
 *    * *
 *     *
 */
#include <stdio.h>
#define LEFT 1  // right shift space

int main(void)
{
        int size = 0;
        printf("Input side number of diamond: ");
        scanf("%d", &size);
        int len = size * 2 - 1;
        int high = len;
        int width = len + LEFT;
        char diamond[high][width];

        const char dia = '*';
        const char pidd = ' ';

//      begin of start and number of diamond
        int begin = 0, n;
        for (int i = 0; i < high; i++) {
                if (i < size) {
                        begin = size - i - 1 + LEFT;
                        n = i + 1;
                } else {
                        begin = i - size + 1;
                        n = size - begin;
                        begin += LEFT;
                }
                for (int j = 0; j < width; j++) {
                        if ((j == begin) && (n--)) {
                                putchar(dia);
                                begin += 2;
                        } else
                                putchar(pidd);
                }
                putchar('\n');
        }

        return 0;
}