C 中的嵌套循环练习 - 我可以写得更好吗?

Dim*_*ris 1 c loops

练习是:

使用嵌套循环产生以下模式

A
BC
DEF
GHIJ
KLMNO
PQRSTU
Run Code Online (Sandbox Code Playgroud)

我写的是这样的:

#include <stdio.h>

int main(void)
{
    char ch[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int x,y;
    int min,max,i;
    min=max=0;
    i=1;
    for(x=0;x<6;x++)
    {
        for(y=min;y<=max;y++){
            printf("%c",ch[y]);
        }
        min=max+1;
        max+=i+1;
        i++;
        printf("\n");
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

有没有一种我想不到的更简单、更好的方法?

Bob*_*ica 5

这是一个替代方案:

#include <stdio.h>

int main(void)
  {
  char c = 'A';

  for(int i = 5 ; i >= 0 ; --i)
    {
    for(int j = i ; j < 6 ; ++j)
      printf("%c", c++);

    printf("\n");
    }
  }
Run Code Online (Sandbox Code Playgroud)

它不是存储所有可能的字符,而是单独打印每个字符,然后在打印后递增该字母。正如预期的那样,输出是:

A
BC
DEF
GHIJ
KLMNO
PQRSTU
Run Code Online (Sandbox Code Playgroud)