I have been wracking my brain over this for hours and I know it has to be something incredibly simple that I'm missing. My assignment is to write a program that sums and averages the contents of an array. I'm required to use separate files.
I think I've narrowed the issue down to my average.cpp file. When summation.cpp is called in main, it sums the numbers just fine. However, in average.cpp the sum does not come out correctly when the array elements are greater than 4 which messes up the average. (Edit: It actually looks like it's adding 10 to what would be the final sum at element 4 then continuing with the correct summation). I'm at a total loss.
Here's an example of the messed up output (I've used cout just to try to figure out where the problem was):
Please assign the size of the array:
7
Please enter the array elements:
1 2 3 4 5 6 7
The sum of the array is: 28.00 (sum function called here)
sum: 1.00
sum: 3.00
sum: 6.00
sum: 10.00
sum: 38.00
sum: 44.00
sum: 51.00
The average of the array is: 7.29
I've posted all of my code below just in case the problem isn't actually in average.cpp.
Line 87: You are creating an array of size 0, then assigning 'size' a different variable. The size of the array will still be 0 as you cannot change the size of an array once its created.
My best guess is that what you are experiencing right now is undefined behavior.
To fix the problem, simply move line 87 to below line 91 i.e., AFTER user has inputted the size, you can them make an array of that size.
But remember in C++ array sizes must be compile time constants. If you want a variable sized array I suggest you consider using a std::vector. Otherwise you'll need to dynamically allocate memory with new[] and delete[] the memory when you're finished.
#include <iostream>
#include <iomanip>
double sum(constdouble* arr, constint size)
{
double total = 0.0;
for(int i = 0; i < size; i++)
{
total += arr[i];
}
return total;
}
double avg(constdouble* arr, constint size)
{
double average = sum(arr, size) / size;
return average;
}
int main()
{
int size = 0;
double num = 0;
std::cout << "Please assign the size of the array: \n";
std::cin >> size;
double* arr = newdouble[size];
std::cout << "Please enter the array elements: \n";
for (int i = 0; i < size; i++)
{
std::cin >> num;
arr[i] = num;
}
std::cout << std::endl;
std::cout << "The sum of the array is: " << sum(arr, size) << std::endl;
std::cout << std::endl;
std::cout << "The average of the array is: " << avg( arr, size ) << std::endl;
delete [] arr;
return 0;
}
Please assign the size of the array:
5
Please enter the array elements:
6
7
2
3
1
The sum of the array is: 19
The average of the array is: 3.8
Exit code: 0 (normal program termination)
Thank you, everyone for your help! Arslan7041, I made the changes you suggested and now it works perfectly. I knew it had to be something simple :) jlb, thank you for the tip as well! I really appreciate it.