How to create an n by n matrix using the C language?
To generate an n-dimensional matrix, you can use a two-dimensional array to represent it. Here is an example code in C language for generating an n-dimensional matrix.
#include <stdio.h>
#define MAX_SIZE 10
void generateSquareMatrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {
int num = 1;
int row = 0, col = n / 2;
// 初始化矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = 0;
}
}
// 生成方阵
while (num <= n * n) {
matrix[row][col] = num;
num++;
// 移动位置
row--;
col++;
// 处理边界和重复数字
if (row < 0 && col >= n) {
row += 2;
col--;
}
else if (row < 0) {
row = n - 1;
}
else if (col >= n) {
col = 0;
}
else if (matrix[row][col] != 0) {
row += 2;
col--;
}
}
}
void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int matrix[MAX_SIZE][MAX_SIZE];
int n;
printf("请输入方阵的阶数:");
scanf("%d", &n);
generateSquareMatrix(matrix, n);
printMatrix(matrix, n);
return 0;
}
In this code snippet, the function generateSquareMatrix is used to create an n x n square matrix and store it in the 2D array matrix. The function printMatrix is used to display the result of the square matrix.
In the main function, the order of the square matrix is first obtained through user input. Next, the generateSquareMatrix function is called to create the square matrix, followed by calling the printMatrix function to output the result.
Please note that the MAX_SIZE macro defines the maximum order of the square matrix, and you can modify this value as needed.