Using Multidimensional Arrays and Functions - C Function

C examples for Function:Function Parameter

Description

Using Multidimensional Arrays and Functions

Demo Code

#include <stdio.h>
void scalarMultiply (int matrix[3][5], int scalar);
void displayMatrix (int matrix [3][5]);
int main (void)
{

    /*w  ww  . j a  v  a2s . c  o  m*/
    int sampleMatrix[3][5] =
    {
        {  1, 6, 5, 13, 12},
        {  2, 3, 2,  3,  7},
        { -2, 1, 2,  4,  9}
    };

    printf("Original matrix:\n");
    displayMatrix(sampleMatrix);

    scalarMultiply(sampleMatrix, 2);

    printf("\nMultiplied by 2:\n");
    displayMatrix(sampleMatrix);

    scalarMultiply(sampleMatrix, -1);

    printf("\nThen multiplied by -1:\n");
    displayMatrix(sampleMatrix);

    return 0;
}

//multiply a 3 x 5 array by a scalar.
void scalarMultiply (int matrix[3][5], int scalar){
    for (int row = 0; row < 3; ++row )
        for (int column = 0; column < 5; ++column )
            matrix[row][column] *= scalar;
}

//print content of a 3 x 5 array.
void displayMatrix (int matrix[3][5]){
    for (int row = 0; row < 3; ++row ){
        for (int column = 0; column < 5; ++column )
            printf("%5i", matrix[row][column]);
        printf ("\n");
    }
}

Related Tutorials