Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.0 kB
4
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

int *createMatrix(int *mat, int r, int c, char letter);
void displayMatrix(int *mat, int r, int c, char letter);

int main(void)
{
    float input1, input2;
    char waste;
    int flag;

    printf("Please enter the size of the first square matrix: ");
    while((flag = scanf("%f", &input1)) != 1 || input1 - (int)input1 != 0 || input1 <= 0){
        if(flag == 0){ // non-number input
            scanf("%s", &waste);
        }
        printf("You have entered an invalid input. Please try again.");
    }

    printf("Please enter the size of the second square matrix: ");
    while((flag = scanf("%f", &input2)) != 1 || input2 - (int)input2 != 0 || input2 <= 0){
        if(flag == 0){ // non-number input
            scanf("%s", &waste);
        }
        printf("You have entered an invalid input. Please try again.");
    }

    int n1 = (int)input1;
    int n2 = (int)input2;

    int matrixA[n1][n1];
    int matrixB[n2][n2];

    int *matA, *matB;
    matA = createMatrix(matrixA, n1, n1, 'A');
    matB = createMatrix(matrixB, n2, n2, 'B');
    puts("");
    displayMatrix(matA, n1, n1, 'A');
    puts("");
    displayMatrix(matB, n2, n2, 'B');

    return 0;
}

int *createMatrix(int *mat, int r, int c, char letter){
    printf("Please enter the elements row-by-row.\n");
    for(int i = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            printf("Matrix %c[%d][%d]: ", letter, i+1, j+1);
            int element;
            scanf("%d", &element);
            *(mat + i*c + j) = element;
        }
    }
}

void displayMatrix(int *mat, int r, int c, char letter){
    printf("Matrix %c in 2D is shown as below\n", letter);
    for(int i = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            printf("%d ", *(mat + i*c +j));
            if(j = c-1){
                printf("\n");
            }
        }
    }
}