C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Interchange rows and columns (Matrix Swap) using Pointers

C Program: Interchange rows and columns (Matrix Swap) using Pointers

C

#include <stdio.h>

 

int main() {

    int a[10][10];

    int *p;

    int rows, cols, i, j, temp;

 

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

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

 

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

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

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

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

        }

    }

 

    p = &a[0][0];  // Pointer to the first element of the matrix

 

    printf("\nOriginal Matrix:\n");

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

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

            printf("%d ", *(p + i * cols + j));

        }

        printf("\n");

    }

 

    // Interchange first and last row using pointers

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

        temp = *(p + 0 * cols + j);

        *(p + 0 * cols + j) = *(p + (rows - 1) * cols + j);

        *(p + (rows - 1) * cols + j) = temp;

    }

 

    // Interchange first and last column using pointers

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

        temp = *(p + i * cols + 0);

        *(p + i * cols + 0) = *(p + i * cols + (cols - 1));

        *(p + i * cols + (cols - 1)) = temp;

    }

 

    printf("\nMatrix after Interchanging First and Last Row, and First and Last Column:\n");

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

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

            printf("%d ", *(p + i * cols + j));

        }

        printf("\n");

    }

 

    return 0;

}

Output

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

Original Matrix:
1 2 3
4 5 6
7 8 9

Matrix after Interchanging First and Last Row, and First and Last Column:
9 8 7
6 5 4
3 2 1

Explanation

  1. The matrix is stored in a 2D array, and a pointer p points to its first element.
  2. Two pointer-based swaps are performed:
    • First ↔ Last Row:
      *(p + 0 * cols + j)*(p + (rows - 1) * cols + j)
    • First ↔ Last Column:
      *(p + i * cols + 0)*(p + i * cols + (cols - 1))
  3. The result is displayed after both swaps.