Why is my program saying that 5 * 5 is equal to 104126025?

83 views Asked by At

I created a function to return the result of all the odd numbers in a vector.

    int oddProduct(std::vector<int> arr) {
    int sum = 1;

    for (int i = 0; i <= arr.size(); i++) {
        if (arr[i] % 2 != 0){
            sum *= arr[i];
            std::cout << " " << arr[i];
            }
         }
    return sum;
    }

The function worked with every other vector I inputted and the print statements even show that the elements of the vector I multiply are both equal to 5. (btw I was using repl.it)

1

There are 1 answers

4
JDługosz On

i <= arr.size()
The legal values of the subscript are 0 through size-1 inclusive.

Use a range-based for statement to avoid the mistake (and the repeated dereferences)