How to generate an n x n matrix in the C programming language?

To generate an n x n matrix, you need to use nested loops to fill in each element of the matrix.

Here is an example code in C language for generating an n x n matrix.

#include <stdio.h>

#define MAX_SIZE 10

int main() {
    int n;
    printf("请输入矩阵的大小(1-%d):", MAX_SIZE);
    scanf("%d", &n);

    if (n < 1 || n > MAX_SIZE) {
        printf("矩阵大小无效!\n");
        return 0;
    }

    int matrix[MAX_SIZE][MAX_SIZE];

    // 生成矩阵
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            matrix[i][j] = i * n + j + 1;
        }
    }

    // 打印矩阵
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%2d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Firstly, the code asks the user to input the size of the matrix (ranging from 1 to 10), then it generates the matrix using a nested loop where each element’s value is calculated. Lastly, it loops through the matrix again and prints it out.

Note: The example code assumes the maximum size of the matrix is 10×10 and restricts user input within this range. You can adjust these limitations as needed.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds