C++ --------------------------- Write a program with two functions. Function one
ID: 3698923 • Letter: C
Question
C++ ---------------------------
Write a program with two functions. Function one will receive as parameters a 2D array and number of rows and columns. It will sum all the elements of the array and return the total. The second function will take the return value from the first function and use it to calculate the average value, as a floating point number. This value should be returned to main. The result of both functions will be presented to the user along with appropriate text.
Example of 2D array:
float box[][] = {{11,8,0,-4}, {74,5,13,42}, {29,-7,45,4}, {100,23,-3,61}};
Explanation / Answer
#include <iostream>
using namespace std;
float getSum(float a[][4], int r, int c) {
float sum = 0;
for(int i=0;i<r;i++) {
for(int j=0;j<c;j++) {
sum+=a[i][j];
}
}
return sum;
}
float getAverage(float total, int r, int c) {
return total/(r+c);
}
int main()
{
float box[4][4] = {{11,8,0,-4}, {74,5,13,42}, {29,-7,45,4}, {100,23,-3,61}};
float sum = getSum(box,4,4);
float average = getAverage(sum, 4,4);
cout<<"Total: "<<sum<<endl;
cout<<"Average: "<<average<<endl;
return 0;
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.