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.

150 Chapter 8 Work<strong>in</strong>g with Functions<br />

The scalarMultiply function is called a second time to multiply the now modified<br />

elements of the sampleMatrix array by –1.The modified array is then displayed by a<br />

f<strong>in</strong>al call to the displayMatrix function, and program execution is then complete.<br />

Multidimensional Variable-Length Arrays and Functions<br />

You can take advantage of the variable-length array feature <strong>in</strong> the C language and write<br />

functions that can take multidimensional arrays of vary<strong>in</strong>g sizes. For example, Program<br />

8.13 can been rewritten so that the scalarMultiply and displayMatrix functions can<br />

accept matrices conta<strong>in</strong><strong>in</strong>g any number of rows and columns, which can be passed as<br />

arguments to the functions. See Program 8.13A.<br />

Program 8.13A Multidimensional Variable-Length Arrays<br />

#<strong>in</strong>clude <br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

void scalarMultiply (<strong>in</strong>t nRows, <strong>in</strong>t nCols,<br />

<strong>in</strong>t matrix[nRows][nCols], <strong>in</strong>t scalar);<br />

void displayMatrix (<strong>in</strong>t nRows, <strong>in</strong>t nCols, <strong>in</strong>t matrix[nRows][nCols]);<br />

<strong>in</strong>t sampleMatrix[3][5] =<br />

{<br />

{ 7, 16, 55, 13, 12 },<br />

{ 12, 10, 52, 0, 7 },<br />

{ -2, 1, 2, 4, 9 }<br />

};<br />

pr<strong>in</strong>tf ("Orig<strong>in</strong>al matrix:\n");<br />

displayMatrix (3, 5, sampleMatrix);<br />

scalarMultiply (3, 5, sampleMatrix, 2);<br />

pr<strong>in</strong>tf ("\nMultiplied by 2:\n");<br />

displayMatrix (3, 5, sampleMatrix);<br />

scalarMultiply (3, 5, sampleMatrix, -1);<br />

pr<strong>in</strong>tf ("\nThen multiplied by -1:\n");<br />

displayMatrix (3, 5, sampleMatrix);<br />

}<br />

return 0;<br />

// Function to multiply a matrix by a scalar<br />

void scalarMultiply (<strong>in</strong>t nRows, <strong>in</strong>t nCols,<br />

<strong>in</strong>t matrix[nRows][nCols], <strong>in</strong>t scalar)

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

Saved successfully!

Ooh no, something went wrong!