68 382
Assignments Done
98,5%
Successfully Done
In November 2018

Answer to Question #72084 in C++ for jesse

Question #72084
Write a C++ program to place random integers, whose values range from -100 to +100, into a
40 element integer array. The user should be able to choose how many values to place into the array.
Have main() output the values. Now call a function to calculate the lists mean average value (in floating point).
This same function should also find the two values in the array whose value is the closest to its average.
Main() should output the average and the two array values closest to the average.
Note: It is possible that the two values closest to the average may be identical.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

double getAverage(int* arr, int size) {
double sum = 0;
for (int i = 0; i < size; i++)
sum += *(arr + i);
return sum / size;
}

void printTwoClose(int* arr, int size, double avrg) {
double dif = avrg - *(arr);
int numb1 = *(arr);
int numb2 = *(arr);
int Loseindex = 0;
for (int i = 1; i < size; i++) {
if (abs(int(avrg - *(arr + i))) < abs(int(dif))) {
numb1 = *(arr + i);
dif = avrg - *(arr + i);
Loseindex = i;
}
}
dif = avrg - *(arr);
for (int i = 1; i < size; i++) {
if (abs(int(avrg - *(arr + i))) < abs(int(dif)) && i != Loseindex) {
numb2 = *(arr + i);
dif = avrg - *(arr + i);
}
}
cout << numb1 << " " << numb2 << endl;
}

void print(int* arr, int size) {
cout << "Array List:\n";
for (int i = 0; i < size; i++)
cout << *(arr + i) << " ";
cout << "\n\n";
}
int main()
{
srand(time(NULL));
int size;
int array[40];
cout << "Input how many elements place into the array:\n";
cin >> size;
for (int i = 0; i < size; i++) {
array[i] = -(rand() % 101) + rand() % 100;
}

print(array, size);
double avrg = getAverage(array, size);
cout << "Average value " << avrg << endl;
printTwoClose(array, size, avrg);

return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!