0

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?

  • You're ignoring the [warnings you should be getting](https://godbolt.org/z/1MP8e9aWo) if compiled with appropriate paranoia levels. Look at the second line of `main` in the first code list. What is the value of `sum`? Hint: the only right answer is "I have no idea", and to that you're in good company because neither does your program. `sum` is defined, but has neither been initialized, nor assigned, a *determinate* value. Therefore `sum += input;` is nonsense. It is asking to add `input` to the previous value of `sum` (which nobody knows) and store the result in `sum`. – WhozCraig Aug 01 '22 at 03:35
  • 1
    Refer to a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). This is explained in any beginner level c++ book. You're using uninitialized variable. – Jason Aug 01 '22 at 03:35

0 Answers0