getRowTotal. This function should accept a two - dimensional array as its first argument and an integer as its second argument. The second argument should be the subscript of a row in the array. The function should return the total of the values in the specified row.
How would one build this function in C++?
This is what I'm working with:
#include <iostream>
#include <iomanip>
using namespace std;
//declare global variables
const int NUM_ROWS = 3;
const int NUM_COLS = 3;
//prototypes
void showArray(int array[][NUM_COLS], int);
int getTotal(int [][NUM_COLS], int, int);
int getAverage(int [][NUM_COLS], int, int);
int getRowTotal(int [][NUM_COLS], int, int);
int main() {
int total = 0;
int average = 0;
int rowTotal = 0;
int smallArray[NUM_ROWS][NUM_COLS] = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
int largeArray[NUM_ROWS][NUM_COLS] = { {10, 20, 30},
{40, 50, 60},
{70, 80, 90} };
I had modified your prototypes.
void showArray( int array[NUM_ROWS][NUM_COLS] )
{
for( int i = 0; i < NUM_ROWS; ++i )
{
for( int j = 0; j < NUM_COLS; ++j )
std::cout << (j > 0 ? ',' : '\0') << array[i][j];
std::cout << std::endl;
}
}
int getTotal( int array[NUM_ROWS][NUM_COLS] )
{
int total = 0;
for( int i = 0; i < NUM_ROWS; ++i )
for( int j = 0; j < NUM_COLS; ++j )
total += array[i][j];
return total;
}
int getAverage( int array[NUM_ROWS][NUM_COLS] )
{
return getTotal( array )/(NUM_ROWS * NUM_COLS);
}
int getRowTotal( int array[NUM_ROWS][NUM_COLS], int row )
{
int total = 0;
if( (row >= 0) && (row < NUM_ROWS) )
{
for( int j = 0; j < NUM_COLS; ++j )
total += array[row][j];
}
return total;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.