+ 2
What's wrong with the code? //array involved//C++
>.< I can't find out why the result is this big and even negative. I want to calculate the sum of the array's elements (the size of the array being given by the user) getting user input for them. the size of the array = n (n given by user) #include <iostream> #include <conio.h> using namespace std; int main(){ int n, i, sum = 0; cout << "Enter the N(number of elements in the array) number: " << endl; cin >> n; cout << n << endl; int *a = new int [n]; cout << "Enter the " << n << " elements of the array" << endl; for (i = 1; i <= n; i++){ cin >> a[i]; } cout << a[i] << " "; cout << endl; sum = sum + a[i]; cout << "The sum of these elements is: " << sum << endl; getch(); return 0; }
5 Answers
+ 9
Can you try it with:
for (i = 0 ; i < n ; i++)
Because indexes begin at 0 and last element has the index n-1.
+ 4
Firstly, an array of size n go from a[0] to a[n-1] and not a[1] to a[n].
Secondly, at the end of the for loop, i is equal to n+1 so when you try to access a[i], you are accessing uninitialized memory space (so there are lots of unknown numbers there).
Lastly, if you wanted to sum the array's value, you should have done a second for loop and not just add to 0 what you think was the last value of the array (I suppose).
Hope it'll help :)
+ 3
Thank you guys. I confused a simple loop with the first index of an array even though I knew it's 0, didn't think about it's importance
+ 2
"for (i = 1; i <= n; i++){
cin >> a[i];
}"
there you are writing to n+1 th cell of the array and ommiting 1st one
for(i=0;i<n;i++) is the right loop
+ 2
You're welcome
No need to justify yourself, we are all here to learn ^^