C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Matrix addition using pointers

C Program: Matrix addition using pointers

C

#include <stdio.h>

 

int main() {

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

    int *p, *q, *r;

    int rows, cols, i, j;

 

    printf("Enter number of rows and columns: ");

    scanf("%d %d", &rows, &cols);

 

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

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

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

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

        }

    }

 

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

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

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

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

        }

    }

 

    // Initialize pointers

    p = &a[0][0];

    q = &b[0][0];

    r = &sum[0][0];

 

    // Matrix addition using pointers

    for (i = 0; i < rows * cols; i++) {

        *(r + i) = *(p + i) + *(q + i);

    }

 

    // Display result

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

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

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

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

        }

        printf("\n");

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter number of rows and columns: 2 2
Enter elements of first matrix:
1 2
3 4
Enter elements of second matrix:
5 6
7 8

Resultant Matrix (Sum):
6 8
10 12

Explanation

  1. Matrices a, b, and sum are declared as 2D arrays.
  2. Pointers p, q, and r are assigned to the base addresses of the matrices.
  3. Using pointer arithmetic:
    • *(r + i) = *(p + i) + *(q + i)
      performs element-wise addition across both matrices.
  4. Finally, the result is displayed in matrix form.