20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Functions and Arrays<br />

149<br />

Program 8.13 Cont<strong>in</strong>ued<br />

pr<strong>in</strong>tf ("\n");<br />

}<br />

}<br />

Program 8.13<br />

Output<br />

Orig<strong>in</strong>al matrix:<br />

7 16 55 13 12<br />

12 10 52 0 7<br />

-2 1 2 4 9<br />

Multiplied by 2:<br />

14 32 110 26 24<br />

24 20 104 0 14<br />

-4 2 4 8 18<br />

Then multiplied by -1:<br />

-14 -32 -110 -26 -24<br />

-24 -20 -104 0 -14<br />

4 -2 -4 -8 -18<br />

The ma<strong>in</strong> rout<strong>in</strong>e def<strong>in</strong>es the matrix sampleValues and then calls the displayMatrix<br />

function to display its <strong>in</strong>itial values at the term<strong>in</strong>al. Inside the displayMatrix rout<strong>in</strong>e,<br />

notice the nested for statements.The first or outermost for statement sequences<br />

through each row <strong>in</strong> the matrix, so the value of the variable row varies from 0 through<br />

2.For each value of row, the <strong>in</strong>nermost for statement is executed.This for statement<br />

sequences through each column of the particular row, so the value of the variable<br />

column ranges from 0 through 4.<br />

The pr<strong>in</strong>tf statement displays the value conta<strong>in</strong>ed <strong>in</strong> the specified row and column<br />

us<strong>in</strong>g the format characters %5i to ensure that the elements l<strong>in</strong>e up <strong>in</strong> the display. After<br />

the <strong>in</strong>nermost for loop has f<strong>in</strong>ished execution—mean<strong>in</strong>g that an entire row of the<br />

matrix has been displayed—a newl<strong>in</strong>e character is displayed so that the next row of the<br />

matrix is displayed on the next l<strong>in</strong>e of the term<strong>in</strong>al.<br />

The first call to the scalarMultiply function specifies that the sampleMatrix array<br />

is to be multiplied by 2. Inside the function, a simple set of nested for loops is set up to<br />

sequence through each element <strong>in</strong> the array.The element conta<strong>in</strong>ed <strong>in</strong><br />

matrix[row][column] is multiplied by the value of scalar <strong>in</strong> accordance with the use<br />

of the assignment operator *=. After the function returns to the ma<strong>in</strong> rout<strong>in</strong>e, the<br />

displayMatrix function is once aga<strong>in</strong> called to display the contents of the<br />

sampleMatrix array.The program’s output verifies that each element <strong>in</strong> the array has, <strong>in</strong><br />

fact, been multiplied by 2.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!