C 语言中输出乘法表的多种方法206
C 语言提供了多种方法来在控制台上输出乘法表。本文将介绍一些常见且有效的技术,并详细解释其语法和用法。
使用嵌套循环
嵌套循环是最简单的方法之一,它可以通过将第一个循环用于行,第二个循环用于列,轻松地生成乘法表。
#include <stdio.h>
int main() {
int rows, columns;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
printf("%d * %d = %d", i, j, i * j);
}
printf("");
}
return 0;
}
使用数组
使用数组也是一个有效的选择,它可以以表格形式存储乘法表。
#include <stdio.h>
int main() {
int rows, columns;
int table[10][10];
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
table[i][j] = (i + 1) * (j + 1);
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d ", table[i][j]);
}
printf("");
}
return 0;
}
使用指针
指针也是一种在 C 语言中输出乘法表的替代方法,它可以提供更直接的内存访问。
#include <stdio.h>
int main() {
int rows, columns;
int *table;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
table = (int *)malloc(rows * columns * sizeof(int));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
*(table + i * columns + j) = (i + 1) * (j + 1);
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
printf("%d ", *(table + i * columns + j));
}
printf("");
}
free(table);
return 0;
}
其他方法
除了上述方法外,还有其他一些方法可以输出乘法表:* 使用递归
* 使用 goto 语句
* 使用宏
2025-02-07
上一篇:C 语言中函数的应用
Java数组元素:从基础到高级操作的深度解析
https://www.shuihudhg.cn/134539.html
PHP Web应用的安全基石:全面解析数据库SQL注入防御
https://www.shuihudhg.cn/134538.html
Python函数入门到进阶:用简洁代码构建高效程序
https://www.shuihudhg.cn/134537.html
PHP中解析与提取代码注释:DocBlock、反射与AST深度探索
https://www.shuihudhg.cn/134536.html
Python深度解析与高效处理.dat文件:从文本到二进制的实战指南
https://www.shuihudhg.cn/134535.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html