On the CSES website, I was solving missing number problem and my original code was this:
#include <iostream>
using namespace std;
int main(){
long long int n, input, sum;
cin >>n;
for (int i = 0; i < n - 1 ; i++){
cin>> input;
sum += input;
}
cout << (n*(n+1))/2-sum << endl;
return 0;
}
However, when I inputted in 5, and then 1,2,3,4, it outputted -3.
But when I change it to this with the sum already set: '''
#include <iostream>
using namespace std;
int main(){
long long int n, input, sum = 0;
cin >>n;
for (int i = 0; i < n - 1 ; i++){
cin>> input;
sum += input;
}
cout << (n*(n+1))/2-sum << endl;
return 0;
}
It gives me the correct output with the same input, which is 5.
Can anyone explain why this happens?