使用兩個參數追蹤狀態:
邏輯:列遞增至 `row` → 換行、行遞增、列重置 1 → 行超過 9 終止
#include
/**
* 遞迴輸出 99 乘法表
* @param row 當前行 (1-9)
* @param col 當前列 (1-row)
*/
void printMultiplicationTable(int row, int col) {
// 終止條件:行超過 9
if (row > 9) return;
// 輸出當前乘法式
printf("%d * %d = %d\t", row, col, row * col);
// 判斷是否換行、移至下一行
if (col >= row) {
// 當前行結束:換行、下一行、列重置為 1
printf("\n");
printMultiplicationTable(row + 1, 1);
} else {
// 同行下一列
printMultiplicationTable(row, col + 1);
}
}
int main() {
// 從第 1 行、第 1 列開始
printMultiplicationTable(1, 1);
return 0;
}
| 遞迴層級 | row | col | 輸出 | 下一步動作 |
|---|---|---|---|---|
| 1 | 1 | 1 | 1*1=1\t | col>=row → 換行, print(2,1) |
| 2 | 2 | 1 | 2*1=2\t | col |
| 3 | 2 | 2 | 2*2=4\t | col>=row → 換行, print(3,1) |
| 4 | 3 | 1 | 3*1=3\t | print(3,2) |
| 5 | 3 | 2 | 3*2=6\t | print(3,3) |
| 6 | 3 | 3 | 3*3=9\t | 換行, print(4,1) |
| ... | ... | ... | ... | ... |
| 45 | 9 | 9 | 9*9=81\t | 換行, print(10,1) |
| 46 | 10 | 1 | - | row>9 → return (結束) |
1 * 1 = 1
2 * 1 = 2 2 * 2 = 4
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81
void printFullTable(int row, int col) {
if (row > 9) return;
if (col > 9) {
printf("\n");
printFullTable(row + 1, 1);
return;
}
printf("%d * %d = %d\t", col, row, col * row); // 注意順序
printFullTable(row, col + 1);
}
遞迴雙計數器 (`row`, `col`) 完美模擬雙層迴圈輸出 99 乘法表。**55 次遞迴呼叫、最大深度 18、尾遞迴優化友善**,是展示「遞迴替代巢狀迴圈」的經典教學範例。實務中請直接用 `for` 迴圈。