1、使用嵌套 for 循环
#include <stdio.h>
int main() {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
printf("%d * %d = %d\t", j, i, i * j);
}
printf("\n");
}
return 0;
}
2、使用 while 循环
#include <stdio.h>
int main() {
int i = 1;
while (i <= 9) {
int j = 1;
while (j <= i) {
printf("%d * %d = %d\t", j, i, i * j);
j++;
}
printf("\n");
i++;
}
return 0;
}
3、使用 do-while 循环
#include <stdio.h>
int main() {
int i = 1;
do {
int j = 1;
do {
printf("%d * %d = %d\t", j, i, i * j);
j++;
} while (j <= i);
printf("\n");
i++;
} while (i <= 9);
return 0;
}
4、使用递归
#include <stdio.h>
void printMultiplicationTable(int i, int j) {
if (i > 9) return;
if (j > i) {
printf("\n");
printMultiplicationTable(i + 1, 1);
} else {
printf("%d * %d = %d\t", j, i, i * j);
printMultiplicationTable(i, j + 1);
}
}
int main() {
printMultiplicationTable(1, 1);
return 0;
}
5、使用单一循环和条件判断
#include <stdio.h>
int main() {
for (int k = 1; k <= 45; k++) {
int i = (k - 1) / 9 + 1;
int j = k % 9 == 0 ? 9 : k % 9;
if (j <= i) {
printf("%d * %d = %d\t", j, i, i * j);
if (j == i) printf("\n");
}
}
return 0;
}
6、使用宏定义
#include <stdio.h>
#define PRINT_TABLE() \
for (int i = 1; i <= 9; i++) { \
for (int j = 1; j <= 9; j++) { \
printf("%d*%d=%2d ", i, j, i * j); \
} \
printf("\n"); \
}
int main() {
PRINT_TABLE();
return 0;
}
7、使用指针和动态内存分配
#include <stdio.h>
#include <stdlib.h>
int main() {
int *table = (int *)malloc(9 * 9 * sizeof(int));
if (table == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
*(table + (i - 1) * 9 + (j - 1)) = i * j;
}
}
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
printf("%d*%d=%2d ", i, j, *(table + (i - 1) * 9 + (j - 1)));
}
printf("\n");
}
free(table);
return 0;
}