C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Matrix Scalar Multiplication using Pointers

C Program: Matrix Scalar Multiplication using Pointers

C

#include <stdio.h>

 

int main() {

    int a[10][10];

    int *p;

    int rows, cols, i, j, scalar;

 

    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]);

        }

    }

 

    printf("Enter scalar value to multiply: ");

    scanf("%d", &scalar);

 

    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");

    }

 

    // Multiply each element of matrix by scalar using pointers

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

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

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

        }

    }

 

    printf("\nMatrix after Scalar Multiplication (× %d):\n", scalar);

    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: 2 3
Enter elements of the matrix:
1 2 3
4 5 6
Enter scalar value to multiply: 3

Original Matrix:
1 2 3
4 5 6

Matrix after Scalar Multiplication (× 3):
3 6 9
12 15 18

Explanation

  • p is a pointer to the first element of the 2D array a.
  • Using pointer arithmetic, each element is accessed as:

*(p + i * cols + j)

  • Each element is multiplied by the scalar and updated in place.