C program to perform Scalar matrix multiplication

Write a C program to read elements in a matrix and perform scalar multiplication of matrix. C program for scalar multiplication of matrix.

Example:
If matrix A=
1 2 3
4 5 6
7 8 9

Output: 2 . A =
2  4  6
8 10 12
14 16 18

Required knowledge:

Basic C programming, For loop, Array, Matrix

Scalar multiplication of matrix

Scalar multiplication of matrix is the simplest and easiest way to multiply matrix. Scalar multiplication of matrix is defined by.
(cA)ij = c . Aij (Where 1 ≤ i ≤ m and 1 ≤ j ≤ n)
Scalar multiplication of matrix

Program:

/**
 * C program to perform scalar multiplication of matrix
 */
 
#include <stdio.h>

int main()
{
    int A[3][3];
    int num, row, col;

    /*
     * Reads elements in matrix from user
     */
    printf("Enter elements in matrix of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /* Reads number to perform scalar multiplication from user */
    printf("Enter any number to multiply with matrix A: ");
    scanf("%d", &num);

    /*
     * Performs scalar multiplication of matrix
     */
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            /* (cAij) = c . Aij */
            A[row][col] = num * A[row][col];
        }
    }

    /*
     * Prints the result of scalar multiplication of matrix
     */
    printf("\nScalar multiplication of matrix A = \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            printf("%d ", A[row][col]);
        }
        printf("\n");
    }

    return 0;
} 
Output
X
_
Enter elements in matrix of size 3x3:
1 2 3
4 5 6
7 8 9
Enter any number to multiply with matrix A: 2

Scalar multiplication of matrix A =
2  4  6
8 10 12
14 16 18

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment