FAQ: Vectors - Review

Hi all, I’m just curious why the code written below outputs seemingly random numbers that change every time the code is run. Does C++ not initialize int to 0 by default?

Initializing int even = 0 and int odd = 1 makes the code run as intended so the issue seems to be wherever the default values are being pulled from.

#include <iostream>
#include <vector>

int main() {

  int even;
  int odd;
  std::vector<int> nums = {2, 4, 3, 6, 1, 9};

  for (int i = 0; i < nums.size(); i++) {
    
    int half = nums[i] / 2;

    if (half + half == nums[i]) {
      
      even = even + nums[i];
    
    }

    else {
      
      odd = odd * nums[i];
    
    }

  }

  std::cout << "Sum of even numbers is " << even << "\n";

  std::cout << "Product of odd numbers is " << odd << "\n";

  }
1 Like

You got it. C++ doesn’t initialize to a default value. You can use cout statements right before you enter your loop to print out the uninitialized variables even and odd.
Here is a useful read on the topic.
https://www.learncpp.com/cpp-tutorial/uninitialized-variables-and-undefined-behavior/

1 Like

I’m the same, I feel really in the dark. It’s okay, with practice I’m sure we’ll both get better. Looking at the answer it seems a lot more complicated than it is and I think it has a lot to do with the fact we haven’t been using the language for long. I know you’re probably finished with this course by now but your comment made me feel so much less alone!