C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Compare Two Matrices using Pointers

C Program: Compare Two Matrices using Pointers

C

#include <stdio.h>

 

int main() {

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

    int *p, *q;

    int rows, cols, i, j, flag = 1;

 

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

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

 

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

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

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

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

        }

    }

 

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

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

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

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

        }

    }

 

    p = &a[0][0];

    q = &b[0][0];

 

    // Compare matrices using pointers

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

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

            if (*(p + i * cols + j) != *(q + i * cols + j)) {

                flag = 0;

                break;

            }

        }

    }

 

    if (flag)

        printf("\nBoth matrices are equal.\n");

    else

        printf("\nMatrices are NOT equal.\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:
1 2
3 4

Both matrices are equal.

Explanation

  • Two matrices a and b are compared using pointers p and q.
  • Each element is accessed with pointer arithmetic:

                         *(p + i * cols + j)

  • If any corresponding elements differ, flag becomes 0.