Programming in C

(Barry) #1
Functions and Arrays 149

printf ("\n");
}
}


Program 8.13 Output


Original matrix:
7 16 55 13 12
12 10 52 0 7
-2 1 2 4 9


Multiplied by 2:
14 32 110 26 24
24 20 104 0 14
-4 2 4 8 18


Then multiplied by -1:
-14 -32 -110 -26 -24
-24 -20 -104 0 -14
4 -2 -4 -8 -18


The mainroutine defines the matrix sampleValuesand then calls the displayMatrix
function to display its initial values at the terminal. Inside the displayMatrixroutine,
notice the nested forstatements.The first or outermost forstatement sequences
through each row in the matrix, so the value of the variable rowvaries from 0 through
2 .For each value of row, the innermost forstatement is executed.This forstatement
sequences through each column of the particular row, so the value of the variable
columnranges from 0 through 4.
The printfstatement displays the value contained in the specified row and column
using the format characters %5ito ensure that the elements line up in the display. After
the innermost forloop has finished execution—meaning that an entire row of the
matrix has been displayed—a newline character is displayed so that the next row of the
matrix is displayed on the next line of the terminal.
The first call to the scalarMultiplyfunction specifies that the sampleMatrixarray
is to be multiplied by 2. Inside the function, a simple set of nested forloops is set up to
sequence through each element in the array.The element contained in
matrix[row][column]is multiplied by the value of scalarin accordance with the use
of the assignment operator *=. After the function returns to the mainroutine, the
displayMatrixfunction is once again called to display the contents of the
sampleMatrixarray.The program’s output verifies that each element in the array has, in
fact, been multiplied by 2.


Program 8.13 Continued
Free download pdf