In: Computer Science
Even Odd Average (C++ LANGUAGE)
Write the following functions:
Function #1
Write the function Print. The function will have one int 1D array n and one int size as parameters. The function will display all the values of n on one line.
Function #2
Write the function AverageEvenOdd. The function will have one int 1D array n and one int size as parameters. The size of the array is given by the parameter int size. Therefore, the function should work on the array of any size. The function will display the sum of all even numbers and odd numbers in n and return the average of all even values and odd numbs in n using two reference parameters.
int main()
{
int a[7] = {1, 3, 2, 9, 6, 4, 2};
double aE, aO;
cout<<"a = ";
Print(a, 7);
AverageEvenOdd(a, 7, aE, aO);
cout<<"Average Even: "<<aE<<endl;
cout<<"Average Odd: "<<aO<<endl<<endl;
return 0;
}
A=1 3 2 9 6 4 2
SUM EVEN=14
SUM ODD=13
AVERAGE EVEN =3.5
AVERAGE ODD=4.33333
Code:
Code as text:
#include <iostream>
using namespace std;
// display values of array on one line
void Print(int n[], int size) {
for (int i = 0; i < size; i++) {
cout << n[i] << " ";
}
cout << endl;
}
// calculate average of even and odd numbers
void AverageEvenOdd(int n[], int size, double &aE, double &aO) {
double sE = 0, sO = 0; // variable to store sum of even and odd numbers
int cE = 0, cO = 0; // variable to store count of even and odd numbers
for (int i = 0; i < size; i++) {
if (n[i] % 2 == 0){
sE += n[i];
cE++;
}
else {
sO += n[i];
cO++;
}
}
aE = sE / cE;
aO = sO / cO;
}
int main() {
int a[7] = {1, 3, 2, 9, 6, 4, 2};
double aE, aO;
cout << "A=";
Print(a, 7);
AverageEvenOdd(a, 7, aE, aO);
cout << "Average Even: " << aE << endl;
cout << "Average Odd: " << aO << endl << endl;
return 0;
}
Sample run:
P.s. Ask any doubts in comments and don't forget to rate the answer.