PART B · PRESCRIBED EXERCISE 06

Read, display and multiply matrices using functions

Understand the algorithm. Run the code.
Explain the result with confidence.

Read the programOpen the playground
Aim & definitionStep-by-step algorithmWorked sampleExtra test cases3 viva answers

LAB B06 · 01

Understand the task.

Aim: Read, display and multiply matrices using functions.

DEFINITION

Matrix multiplication. For A with r rows and s columns and B with s rows and c columns, the product C has r rows and c columns. Each C[i][j] is the dot product of row i of A and column j of B.

Review the related theory in Unit 4.

LAB B06 · 02

Know what goes in and what comes out.

First r1 c1 r2 c2, each 1–5. Require c1 = r2. Then enter A row by row, followed by B row by row. Matrix values range from -20 to 20.

Sample input

2 3 3 2
1 2 3
4 5 6
7 8
9 10
11 12

Expected output

Matrix A (2 x 3):
1 2 3
4 5 6
Matrix B (3 x 2):
7 8
9 10
11 12
Product (2 x 2):
58 64
139 154

Source programs read the documented input directly, without prompt text, so the same sample works in the embedded compiler’s STDIN field.

LAB B06 · 03

Plan the steps before writing code.

  1. Read and validate four dimensions. Reject incompatible inner dimensions.
  2. Call readMatrix for A and B; stop if either input is invalid.
  3. For each output row i and column j, initialize product[i][j] to zero.
  4. For each shared index k, add a[i][k] × b[k][j] to that output cell.
  5. Use displayMatrix to display A, B and their product.

LAB B06 · 04

One complete program. Ready to run.

Read, display and multiply matrices using functionsmain.c
#include <stdio.h>
#define MAX 5
int readMatrix(int matrix[][MAX], int rows, int columns);
void displayMatrix(int matrix[][MAX], int rows, int columns);
void multiplyMatrices(int a[][MAX], int b[][MAX], int product[][MAX], int rows, int shared, int columns);
int main(void)
{
    int a[MAX][MAX], b[MAX][MAX], product[MAX][MAX];
    int r1, c1, r2, c2;
    if (scanf("%d%d%d%d", &r1, &c1, &r2, &c2) != 4 ||
        r1 < 1 || r1 > MAX || c1 < 1 || c1 > MAX || r2 < 1 || r2 > MAX || c2 < 1 || c2 > MAX) {
        puts("Enter four dimensions from 1 to 5."); return 1;
    }
    if (c1 != r2) { puts("Cannot multiply: columns of A must equal rows of B."); return 1; }
    if (!readMatrix(a, r1, c1) || !readMatrix(b, r2, c2)) {
        puts("Enter matrix values from -20 to 20."); return 1;
    }
    multiplyMatrices(a, b, product, r1, c1, c2);
    printf("Matrix A (%d x %d):\n", r1, c1); displayMatrix(a, r1, c1);
    printf("Matrix B (%d x %d):\n", r2, c2); displayMatrix(b, r2, c2);
    printf("Product (%d x %d):\n", r1, c2); displayMatrix(product, r1, c2);
    return 0;
}
int readMatrix(int matrix[][MAX], int rows, int columns)
{
    int i, j;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            if (scanf("%d", &matrix[i][j]) != 1 || matrix[i][j] < -20 || matrix[i][j] > 20) return 0;
        }
    }
    return 1;
}
void displayMatrix(int matrix[][MAX], int rows, int columns)
{
    int i, j;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) printf("%s%d", j ? " " : "", matrix[i][j]);
        putchar('\n');
    }
}
void multiplyMatrices(int a[][MAX], int b[][MAX], int product[][MAX], int rows, int shared, int columns)
{
    int i, j, k;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            product[i][j] = 0;
            for (k = 0; k < shared; k++) product[i][j] += a[i][k] * b[k][j];
        }
    }
}
EXPECTED OUTPUTMatrix A (2 x 3): 1 2 3 4 5 6 Matrix B (3 x 2): 7 8 9 10 11 12 Product (2 x 2): 58 64 139 154

Try this programDownload B06-matrix-multiply.c
Compile on your own computer
gcc B06-matrix-multiply.c -o program

Run the generated program and enter the sample input. The examples use standard C90-compatible syntax and explicit function declarations. For these learning programs, enter numeric values representable in the stated C types and within the documented ranges.

LAB B06 · 05

Connect each statement to its purpose.

  • readMatrix, displayMatrix and multiplyMatrices separate input, presentation and calculation. Their prototypes appear before main.
  • The compatibility condition is columns of A = rows of B, not equality of all four dimensions.
  • The product shape is rows of A × columns of B.
  • Initialize each output cell before its k loop; += on an uninitialized cell would read an indeterminate value.
  • For these limits, each product cell sums at most five terms of magnitude 400, so its magnitude is at most 2000.
  • MAX in each 2D-array parameter gives the actual row stride of the fixed arrays, even when the entered number of columns is smaller.

LAB B06 · 06

Follow the sample calculation.

Step or componentWhat happens
ShapesA: 2 × 3, B: 3 × 2 → product: 2 × 2
C[0][0]1 × 7 + 2 × 9 + 3 × 11 = 58
C[0][1]1 × 8 + 2 × 10 + 3 × 12 = 64
Second row4 × 7 + 5 × 9 + 6 × 11 = 139; 4 × 8 + 5 × 10 + 6 × 12 = 154

LAB B06 · 07

Check more than one input.

Try this input or caseExpected behaviour
Multiply by an appropriately sized identity matrixThe other matrix is unchanged.
1 × 1: -20 and 20Product = -400.
A: 2 × 3, B: 2 × 2Rejected: inner dimensions do not match.

Time and storage

O(r1 × c1 × c2) calculation time, plus input/display work. Three fixed-capacity matrices store the inputs and product.

Start with the sample, then test a boundary and a case that changes the result. A correct sample alone does not establish that every input is handled correctly.

LAB B06 · 08

Use the real C compiler.

Choose an example and load it into the embedded C compiler. Select I/O inside the compiler, check the sample STDIN, and press Run. Change the input or edit the source to explore a different case.

Sample input (STDIN)

2 3 3 2
1 2 3
4 5 6
7 8
9 10
11 12

Expected output

Matrix A (2 x 3):
1 2 3
4 5 6
Matrix B (3 x 2):
7 8
9 10
11 12
Product (2 x 2):
58 64
139 154

Load the compiler when you’re ready to practise.

Your C workspace

Edit real C code and see real compiler output.

Compiler provided by OneCompiler. Opening the editor connects to that service; code and input you run are processed there. If the embed is unavailable, open the C compiler in a new tab and paste the source below.

View / copy the selected source
#include <stdio.h>
#define MAX 5
int readMatrix(int matrix[][MAX], int rows, int columns);
void displayMatrix(int matrix[][MAX], int rows, int columns);
void multiplyMatrices(int a[][MAX], int b[][MAX], int product[][MAX], int rows, int shared, int columns);
int main(void)
{
    int a[MAX][MAX], b[MAX][MAX], product[MAX][MAX];
    int r1, c1, r2, c2;
    if (scanf("%d%d%d%d", &r1, &c1, &r2, &c2) != 4 ||
        r1 < 1 || r1 > MAX || c1 < 1 || c1 > MAX || r2 < 1 || r2 > MAX || c2 < 1 || c2 > MAX) {
        puts("Enter four dimensions from 1 to 5."); return 1;
    }
    if (c1 != r2) { puts("Cannot multiply: columns of A must equal rows of B."); return 1; }
    if (!readMatrix(a, r1, c1) || !readMatrix(b, r2, c2)) {
        puts("Enter matrix values from -20 to 20."); return 1;
    }
    multiplyMatrices(a, b, product, r1, c1, c2);
    printf("Matrix A (%d x %d):\n", r1, c1); displayMatrix(a, r1, c1);
    printf("Matrix B (%d x %d):\n", r2, c2); displayMatrix(b, r2, c2);
    printf("Product (%d x %d):\n", r1, c2); displayMatrix(product, r1, c2);
    return 0;
}
int readMatrix(int matrix[][MAX], int rows, int columns)
{
    int i, j;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            if (scanf("%d", &matrix[i][j]) != 1 || matrix[i][j] < -20 || matrix[i][j] > 20) return 0;
        }
    }
    return 1;
}
void displayMatrix(int matrix[][MAX], int rows, int columns)
{
    int i, j;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) printf("%s%d", j ? " " : "", matrix[i][j]);
        putchar('\n');
    }
}
void multiplyMatrices(int a[][MAX], int b[][MAX], int product[][MAX], int rows, int shared, int columns)
{
    int i, j, k;
    for (i = 0; i < rows; i++) {
        for (j = 0; j < columns; j++) {
            product[i][j] = 0;
            for (k = 0; k < shared; k++) product[i][j] += a[i][k] * b[k][j];
        }
    }
}

LAB B06 · 09

Explain why the program works.

Why are there three loops?

i selects an output row, j an output column, and k sums all corresponding row-column products.

Is A × B always equal to B × A?

No. Matrix multiplication is generally not commutative; the reverse product may even have incompatible dimensions.

Why pass dimensions separately?

The function’s pointer parameter does not carry the entered shape. The dimensions define which stored elements are meaningful.

LAB B06 · 10

Build the next skill.

Read the viva answers, try the extra cases, and return to the lab index to mark this exercise as practised.