【C Primer Plus】打印字母金字塔

编写一个程序,提示用户输入大写字母。
使用嵌套循环以下面金字塔型的格式打印字母。
        A       
       ABA
      ABCBA
     ABCDCBA
    ABCDEDCBA
打印这样的图形,要根据用户输入的字母来决定。
例如,上面的图形是在输入E后的打印结果。
#include <stdio.h>
int main()
{
    char start = 'A';
    char end;
    char ch = start;

    printf("Please enter an character:");
    scanf("%c", &end);

    for (int i = 0; i <= end - start; i++, ch = start)
    {
        for (int j = 0; j < end - start - i; j++) // 打印空格
        {
            printf(" ");
        }
        for (int k = 0; k <= i; k++) // 打印升序字母
        {
            printf("%c", ch);
            ch++;
        }
        ch -= 2; // 上一个for循环结束时ch++多执行了一次
        for (int l = 0; l < i; l++) // 打印降序字母
        {
            printf("%c", ch);
            ch--;
        }
        printf("\n");
    }

    return 0;
}

在这里插入图片描述

发布了75 篇原创文章 · 获赞 267 · 访问量 5234

猜你喜欢

转载自blog.csdn.net/weixin_45961774/article/details/104913662