C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Matrix multiplication using pointers

C Program: Matrix multiplication using pointers

C

#include <stdio.h>

 

int main() {

    int a[10][10], b[10][10], result[10][10];

    int *p, *q, *r;

    int i, j, k, rows1, cols1, rows2, cols2;

 

    printf("Enter rows and columns of first matrix: ");

    scanf("%d %d", &rows1, &cols1);

 

    printf("Enter rows and columns of second matrix: ");

    scanf("%d %d", &rows2, &cols2);

 

    // Check if multiplication is possible

    if (cols1 != rows2) {

        printf("Matrix multiplication not possible!\n");

        return 0;

    }

 

    // Input elements for first matrix

    printf("Enter elements of first matrix:\n");

    for (i = 0; i < rows1; i++) {

        for (j = 0; j < cols1; j++) {

            scanf("%d", &a[i][j]);

        }

    }

 

    // Input elements for second matrix

    printf("Enter elements of second matrix:\n");

    for (i = 0; i < rows2; i++) {

        for (j = 0; j < cols2; j++) {

            scanf("%d", &b[i][j]);

        }

    }

 

    // Initialize pointers

    p = &a[0][0];

    q = &b[0][0];

    r = &result[0][0];

 

    // Initialize result matrix to zero

    for (i = 0; i < rows1 * cols2; i++) {

        *(r + i) = 0;

    }

 

    // Matrix multiplication using pointers

    for (i = 0; i < rows1; i++) {

        for (j = 0; j < cols2; j++) {

            for (k = 0; k < cols1; k++) {

                *(r + i * cols2 + j) += (*(p + i * cols1 + k)) * (*(q + k * cols2 + j));

            }

        }

    }

 

    // Display result

    printf("\nResultant Matrix (Product):\n");

    for (i = 0; i < rows1; i++) {

        for (j = 0; j < cols2; j++) {

            printf("%d ", result[i][j]);

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter rows and columns of first matrix: 2 3
Enter rows and columns of second matrix: 3 2
Enter elements of first matrix:
1 2 3
4 5 6
Enter elements of second matrix:
7 8
9 10
11 12

Resultant Matrix (Product):
58 64
139 154

Explanation

  1. Pointer arithmetic is used to access matrix elements instead of array indices.
    • Element (i, j) is accessed as *(p + i * cols + j).
  2. The nested loops perform standard matrix multiplication.
  3. Before multiplication, the program ensures the column count of the first matrix equals the row count of the second.