Hey guys, pretty new to c++ and we had to manipulate the elements of the array through specific functions. The input and display functions work, however, the min, max, avg and sum value that get outputted aren't correct. What's wrong with my code and how can I fix it?
#include <iostream>
using namespace std;
int array [5];
void input (int num);
void display (int num);
int statistics ( int max, int min, int avg, int sum);
cout << "The min is: " << min << endl;
cout << "The max is: " << max << endl;
cout << "The avg is: " << avg << endl;
cout << "The sum is: " << sum << endl;
}
void input (int num) {
for (int num = 1; num < 6; num++) {
cout << "Enter element " << num << ": ";
cin >> array [num];
}
int statistics(int array[], int size) {
max = array[1];
min = array[1];
avg = array[1];
for (int num = 1; num <6; num++) {
if (min > array[num])
min = array[num];
elseif (max < array[num])
max = array[num];
sum += array[num];
avg += array[num];
}
}
}
max, avg, and sum are not visible in that function. And that definition does not match the declaration at the top of the file.
If you want to change the values of max, sum, avg, and min inside of "statistics", you'll have to pass those by reference instead of by value. If you send them by value, a copy is created when the function is called and the original ones never actually get changed.
Initialize your variables in main. Some compilers these days will flat out fail to compile if you do not initialize variables.
your array indexing is wrong, an array index always begins with 0, not 1, so your for loop is skipping the first element of your array
also, your function is void so it does not return anything, but then in your main you output max,min,avg etc, you need to pass these by reference so any changes made in the function which uses these variables, when it executes and goes back to main, your elements will be updated
avg+= array[num]... this is not how you compute the average, avg+=sum/5
How would I make sure to pass the variables by reference instead of values? I thought that arrays automatically passed by reference?
Thanks for all the help!
You can declare the function as int statistics ( int &max, int &min, int &avg, int &sum);. The '&' sends it by reference. This will cause any change in the values inside "statistics" to be reflected in the ones declared in "main".
Make sure your function definition below also has the same signature.