輸入字串長度 n,輸出 n 行,每行長度 n:
#include <stdio.h>
#include <string.h>
void printNPattern(const char *str) {
int n = strlen(str);
if (n == 0) return;
for (int line = 0; line < n; line++) {
char ch = str[line];
if (line == 0 || line == n - 1) {
// 首尾行
printf("%c", ch);
for (int s = 0; s < n - 2; s++) printf(" ");
printf("%c\n", ch);
} else {
// 中間行
printf("%c", ch);
for (int s = 0; s < line - 1; s++) printf(" ");
printf("%c", ch);
for (int s = 0; s < n - line - 2; s++) printf(" ");
printf("%c\n", ch);
}
}
}
int main() {
char input[100];
printf("輸入字串: ");
scanf("%99s", input);
printNPattern(input);
return 0;
}
輸入: ABCD
輸出:
A A
B B
C C
D D
n,決定行數與寬度。line,依規律計算空格數量。n=1 時僅輸出單字元;n=2 時首尾行相同。n ≤ 80。觀察圖形規律、抽象空格數量公式、單層迴圈即可完成任意長度字串的 N 字圖形列印,是經典的迴圈邏輯練習題。