help with taking sum of values within anarrays

Hi i have this assignment about making a program that urges the user to input the number of values to average. Then the program asks user to input the values one by one. I have made this program. i entered the number of values = 5
the numbers are 1,2,3,4,5. the total must be 15 but the compiler gives me the answer 21. i have no idea what to do do and i cant figure whats wrong inn my code please help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <iostream>
#include <string>
using namespace std;
int main () {
    int a,b,c,sum;
    cout<<"Enter the number for values for average:-   ";
    cin>>a;
    int arrayone[a];
    cout<<endl;
    for (b=0;b<a;b++)
             {cout<<"["<<b<<"] =   ";
             cin>>c;
             cout<<endl;
             sum+= arrayone[a];
             }
    
      cout<<sum<<endl;
                    system("pause");
}
             
      
Line 8: Support for VLA is not in standard yet. When the compiler compiles the program, it writes down how much each variable needs memory from stack. However, the value of 'a' is unknown at compile-time and therefore the size of 'arrayone' cannot be known at that point. One can use dynamic allocation to reserve memory from heap during runtime. There is keyword new, but you would be better of learning to use std::vector instead.

That, however, is not your immediate problem. You do store a value written by user into 'c', but you newer use it anywhere. What you do add to the sum is arrayone[a] and such element does not even exists, because the arrayone has only 'a' elements, and their indices are from 0 to a-1.

Furthermore, you don't even need any array for the computation of the average.

Another hint: static_cast<double>(sum) / a
Topic archived. No new replies allowed.