/* * ====================================================================== * Demonstrate Passing of Multi-dimensional Subarrays to Functions * * Copyright (C) 1994-96 by Mark Austin and David Mazzoni. * * This software is provided "as is" without express or implied warranty. * Permission is granted to use this software on any computer system, * and to redistribute it freely, subject to the following restrictions: * * 1. The authors are not responsible for the consequences of use of * this software, even if they arise from defects in the software. * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. * 4. This notice is to remain intact. * ====================================================================== */ #include enum { NoRows = 3, NoCols = 2 }; /* sizes/limits */ int main( void ) { static float faaVals[NoRows][NoCols] = { { 1.0, 2.0 }, { 3.0, 4.0 }, { 5.0, 6.0 } }; float fRowSum, /* sum of rows in array */ fColSum; /* sum of columns in array */ int iRow, iCol; /* row and column indices */ /* function declarations */ float sumRow( float faRow[ NoCols], int iTotalCols ); float sumColumn( float faaMatrix[NoRows][NoCols], int iColNumber, int iTotalRows ); /* [a] : Compute and print sum of each row in array */ printf( "Pass subarrays to sum each of the rows.\n" ); for( iRow = 0; iRow < NoRows; ++iRow ) { fRowSum = sumRow( faaVals[ iRow ], NoCols ); printf( "Sum of Row %i = %3.1f\n", iRow, fRowSum ); } /* [a] : Compute and print sum of each column in array */ printf( "Compute sum of columns in the matrix.\n" ); for( iCol = 0; iCol < NoCols; ++iCol ) { fColSum = sumColumn( faaVals, iCol, NoRows ); printf( "Sum of column %i = %3.1f\n", iCol, fColSum ); } } /* * =========================== * Sum the elements in one row * =========================== */ float sumRow( float faVals[ NoCols ], int iTotalCols ) { int iCol; float fSum = 0.F; for( iCol = 0; iCol < iTotalCols; ++iCol ) fSum += faVals[iCol]; return fSum; } /* * ================================================ * Sum elements in a single column of the 2D matrix * ================================================ */ float sumColumn( float faaMatrix[NoRows][NoCols], int iColNumber, int iTotalRows ) { int iRow; float fSum = 0.F; for( iRow = 0; iRow < iTotalRows; ++iRow ) fSum += faaMatrix[iRow][iColNumber]; return fSum; }