waaaa

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

void createMatrix(int r, int c, int mat[r][c], char letter);
void displayMatrix(int r, int c, int mat[r][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;
    createMatrix(n1, n1, matrixA, 'A');
    createMatrix(n2, n2, matrixB, 'B');
    puts("");
    displayMatrix(n1, n1, matrixA, 'A');
    puts("");
    displayMatrix(n2, n2, matrixB, 'B');

    return 0;
}

void createMatrix(int r, int c, int mat[r][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][j] = element;
        }
    }
}

void displayMatrix(int r, int c, int mat[r][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][j]);
            if (j == c - 1)
            {
                printf("\n");
            }
        }
    }
}