You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过for循环遍历字符数组输出逐行递增的直角三角形图案

实现思路

核心逻辑是先按行计算当前行的字符起始索引,再每行输出对应数量的字符:

  • 第k行(行号从1开始计数)需要输出k个字符,前k-1行累计消耗的字符总数为 1+2+...+(k-1) = k*(k-1)/2,也就是当前行的起始数组索引
  • 外层循环控制行数,内层循环控制当前行输出的字符数量,字符之间加空格分隔,每行结束后换行
  • 遍历过程中要判断索引不超过字符串总长度,避免越界访问
完整代码示例
#include <stdio.h>
#include <string.h>

int main() {
    char string[50] = "Assignment";
    int len = strlen(string);
    int current_index = 0; // 记录当前已使用的数组索引
    int line_char_count = 1; // 当前行需要输出的字符数量

    while (current_index < len) {
        // 每行输出对应数量的字符,到字符串末尾自动停止
        for (int i = 0; i < line_char_count && current_index < len; i++) {
            printf("%c ", string[current_index]);
            current_index++;
        }
        printf("\n");
        line_char_count++;
    }
    return 0;
}
运行效果

和你给出的预期输出完全一致:

A 
s s 
i g n 
m e n t 

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:51:04