1.) Write a C++ program that includes two functions named calcavg() and variance
ID: 639894 • Letter: 1
Question
1.) Write a C++ program that includes two functions named calcavg() and variance(). The calcavg() function should calculate and return the average of values stored in an array named testvals. The array should be declared in main() and include the values 89, 95, 72, 83, 99, 54, 86, 75, 92, 73, 79 75, 82, and 73. The variance is obtained by subtracting the average from each value in testvals, squaring the values obtained, adding them, and dividing by the number of elements in testvals. The values returned from calcavg() and variance() should be displayed by using cout statements in main(). You must use loops to process the array data.
-----------------------------------------------------------
2.) Write a C++ program that adds equivalent elements of the two-dimensional arrays named first and second. Both arrays should have two rows and three columns. For example, element [1][2] of the resulting array should be the sum of first[1][2] and second[1][2]. You must use nested loops to process and display the arrays. The first and second arrays should be initialized as follows:
first second
16 18 23 24 52 77
54 91 11 16 19 59
Explanation / Answer
#include <iostream>
using namespace std;
double calcavg(int arr[], int size){
double sum = 0;
for(int i = 0; i < size; ++i){
sum += arr[i];
}
return sum / size;
}
double variance(int arr[], int size, double avg){
double var = 0;
for(int i = 0; i < size; ++i){
var += (arr[i] - avg) * (arr[i] - avg);
}
return var / size;
}
int main(){
int arr[] = {89, 95, 72, 83, 99, 54, 86, 75, 92, 73, 79, 75, 82, 73};
int size = sizeof(arr) / sizeof(arr[0]);
double avg = calcavg(arr, size);
double var = variance(arr, size, avg);
cout << "Average: " << avg << endl;
cout << "Variance: " << var << endl;
return 0;
}
__________________________________________________________________________________
#include <iostream>
using namespace std;
int main(){
int first[2][3] = {{16, 18, 23}, {54, 91, 11}};
int second[2][3] = {{24, 52, 77}, {16, 19, 59}};
int third[2][3] = {0};
cout << "Third: " << endl;
for(int i = 0; i < 2; ++i){
for(int j = 0; j < 3; ++j){
third[i][j] = first[i][j] + second[i][j];
cout << third[i][j] << " ";
}
cout << endl;
}
cout << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.