C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Sum of Rows and Columns using Pointers

C Program: Sum of Rows and Columns using Pointers

C

#include <stdio.h>

 

int main() {

    int a[10][10];

    int *p;

    int rows, cols, i, j;

    int rowSum, colSum;

 

    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 matrix base address

 

    // Display matrix

    printf("\nMatrix:\n");

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

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

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

        }

        printf("\n");

    }

 

    // Sum of each row

    printf("\nSum of each row:\n");

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

        rowSum = 0;

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

            rowSum += *(p + i * cols + j);

        }

        printf("Row %d = %d\n", i + 1, rowSum);

    }

 

    // Sum of each column

    printf("\nSum of each column:\n");

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

        colSum = 0;

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

            colSum += *(p + i * cols + j);

        }

        printf("Column %d = %d\n", j + 1, colSum);

    }

 

    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

Matrix:
1 2 3
4 5 6
7 8 9

Sum of each row:
Row 1 = 6
Row 2 = 15
Row 3 = 24

Sum of each column:
Column 1 = 12
Column 2 = 15
Column 3 = 18


Explanation

  1. The matrix elements are read and stored in a 2D array.
  2. A pointer p is assigned the address of the first element of the matrix (&a[0][0]).
  3. The program uses pointer arithmetic to calculate sums:
    • Row-wise element: *(p + i * cols + j)
    • Column-wise element: *(p + i * cols + j)
  4. The row and column sums are displayed separately.