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/

2 Likes

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!

I have no issues compiling the program in Codecademy’s IDE. But I tried to compile this using my local computer, I got this error. I’m not sure what exactly is the issue.

#include
#include

int main(){

int total_even = 0;

int prod_odd = 0;

std::vector test = {2, 4, 3, 6, 1, 9};

for (int i = 0; i < test.size(); i++) {

if ( test[i] % 2 == 0){

total_even = total_even + test[i];

}

std::cout << total_even;

}

}

266121212 not 12
I dont see my error, please help. :frowning:

Have a close look at which statements are part of the loop.

1 Like

Wow, that was a really silly mix up.
I was looping the std::out wasnt I?

Thank you so much.

1 Like

So, in my for loop, I set the end condition to be <= .size(), so I ended up getting index 7 of a 6 index vector. Interestingly, it had 4113 as that value, so I was getting some absurd number for the products. Anyone know why that index has that value? Shouldn’t it be 0 if it’s not defined?

#include <iostream>
#include <vector>

int main()
{
  std::vector <int> numbers = {2, 4, 3, 6, 1, 9};
  int sum_of_evens = 0;
  int prod_of_odds = 1;

  for (int i = 0; i < numbers.size(); i++)
  {
    if (numbers[i] % 2 == 0)
    {
      sum_of_evens += numbers[i];
      std::cout << numbers[i] << " is even, adding to sum...\n";
    }
    else if (numbers[i] % 2 != 0)
    {
      prod_of_odds *= numbers[i];
      std::cout << numbers[i] << " is odd, multiplying...\n";
    }
  }
  std::cout << "The sum of the even numbers is: " << sum_of_evens << "\n";
  std::cout << "The product of the odd numbers is: " << prod_of_odds << "\n";
  std::cout << numbers[6];

}

The last line outputs 4113 in my terminal…

It depends on the language. In many languages such as Python, you will get an error if you try to access an invalid index. In C++, there is no guarantee that an error will be raised. Instead, you are liable to get undefined behavior.

In C++, when you are using square bracket notation to access elements of the vector, then you are responsible for not trying to use indices which may be out of range.
Instead if you did something like std::cout << numbers.at(6); , you will see an out of range exception being thrown and the program will crash.
So, if you want to use square brackets to access vector elements, then in C++ you must ensure that you don’t go out of bounds. Instead of square brackets, if you use the at function, then you will be made aware that something has gone wrong.

Have a look at the short paragraph titled “Array bounds checking” in http://www.dcs.bbk.ac.uk/~roger/cpp/week6.htm

2 Likes

Great info, thank you!

Ok I’m having trouble understanding the significance of a line in the for loop.

for (int i = 0; i < vector.size(); i++) {
if (vector[i] % 2 == 0) {
toteven = toteven + vector[i]

particularly what is the purpose of the [i] in vector [i]
is it because it is an intiger, if thats the case and we had doubles would it be [d]?

The variable i is used to keep track of the index.

It does not matter which letter you use for that, as long as you’re consistent … change every i variable to be j for example, and it will still do the same thing.

The idea is that you’re accessing stuff at different positions in vector.
For example, vector[3] would get stuff in vector at index 3.

This is done in a for loop here,
so i starts as being 0 … and you have vector[0] on that iteration
next, i is 1 … and you have vector[1] on that iteration
next, i is 2 … and you have vector[2] on that iteration
and so on …
but it stops when i reaches the size of the vector (meaning the last iteration is when i is one less than the size).

2 Likes

Thank you so much!!! I was racking my head around the concept for so long.

1 Like

Just finished my code and want to share with people.
#include

#include

using namespace std;

int main(){

vector array = {2, 4, 3, 6, 1, 9};

double i, sumE;

int sumO;

for (i = 0; i < array.size(); i++){

if (array[i] % 2 == 0){

  sumE = sumE + array[i];

} else {

  sumO = sumO * array[i];

}

}

cout << "Sum of even numbers is " << sumE <<endl;

cout << "Sum of odd numbers is " << sumO <<endl;

return 0;

}

This is my code and I cannot for the life of me understand why it doesn’t work. It gives the sum 2 and the product 1, and to me it looks virtually identical to the solution. Maybe you guys can let me know. I also noticed that in my code I get a compilation error if I don’t declare i before the for. In the solution, i is not declared before the for and it still works.

#include <iostream> #include <vector> int main() { std::vector<int> numbers = {2, 4, 3, 6, 1, 9}; int sum = 0; int product = 1; int i; for (int i = 0; i < numbers.size(); i++); { if (numbers[i] % 2 == 0) { sum = sum + numbers[i]; } else { product = product * numbers[i]; } } std::cout << "Sum of even numbers is " << sum << ". \n"; std::cout << "Product of odd numbers is " << product << ". \n"; }

That’s a pretty good clue. If you read the error message, it’s an even better clue.

script.cpp: In function ‘int main()’:
script.cpp:14:15: error: ‘i’ was not declared in this scope
   if (numbers[i] % 2 == 0) {
               ^

The error is telling you that i isn’t defined (has not been declared) inside the loop. How can that be when you clearly declared it here:

for (int i = 0; i < numbers.size(); i++)

Examine the entire line where your for loop starts. See anything amiss?

Hint

Take a close look at your for loop:

for (int i = 0; i < numbers.size(); i++); {
// what is this doing here?             ^
  if (numbers[i] % 2 == 0) {

    sum = sum + numbers[i];

  } else {

    product = product * numbers[i];

  }
}
2 Likes

For some reason my product calculates as 0. However, if I change product for a sum works perfect. Dont understand what is the problem

#include <iostream>
#include <vector>
using namespace std;

int main () {
  vector<int> v1={2,4,3,6,1,9};

  int total_even = 0;
  int total_odd =0;

  for (int i=0; i < v1.size(); i++) {
    if(v1[i]%2 == 0)
    total_even = total_even + v1[i];
    else{
    total_odd = total_odd * v1[i];}
  }

  cout << "Sum of even numbers is " << total_even << endl;
  cout << "Product of odd numbers is " << total_odd << endl;
  return 0;
}

Figured it out; had to start with 1 for the product