i tried to solve hackerrank simple Array sum with my code like this
#include <bits/stdc .h>
#include <iostream>
using namespace std;
int main(){
int n;
int arr[n];
int sum = 0;
cin >> n;
for (int i= 0; i < n;i ){
cin >> arr[i];
sum = arr[i];
}
cout<<sum<<endl;
return sum;
}
but the output is not as expected
with the input n is 6 and array input is [1 2 3 4 10 11] and the expected output is 31 but with my code the output is 10
i also tried my code in online complier and the output 31 its as expected as a hackerrank output
can someone help me explain what wrong with my code?
CodePudding user response:
Don't use <bits/stdc .h>
; it's not a standard C library. Including <iostream>
is enough.
The problem is the declaration int arr[n]
: it's not legal in C to declare a variable length array. Your compiler might accept it for compatibility with C, but if you turn on warnings it should have told you about this. But the bigger problem is that at that point, n
is not initialized, so it's undefined how much space it will even reserve for arr
. If you need an array of dynamic size, use std::vector
.
Note that if you just want to calculate the sum of all inputs, there is no need to store the input in an array to begin with.
CodePudding user response:
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int sum = 0;
for (int i= 0; i < n;i ){
cin >> arr[i];
sum = arr[i];
}
cout<<sum<<endl;
return 0;
}