C++ while loop condition ordering

Hi. Hope it’s fine to seek help with other languages here, wasn’t sure where else to go.
“Given a vector of integers, determine how many integers are present before you see the value -99 . Note, it’s possible -99 is not in the vector! If -99 is not in the vector then the result will be equal to the number of elements in the vector.”

Why is it that these while loop conditions are valid:

while( index < vec.size() && vec.at(index) != -99 )

However once it’s flipped:

 while(vec.at(index) != -99 && (index < vec.size()) )

It throws an error?

Remember that with &&, the second half is only evaluated is the first half is true.

1 Like

Also, in the future, more information would be helpful. What is the error? What is vec? Have you confirmed what the current state of vec is, logged it out? What is the rest of the code?

So vec is supposed to be some array of integers. This task is part of a udemy course and the contents of vec are “in the background”?

Hopefully this helps.

Thanks for your earlier response. So in the case of the error, the second condition is not evaluated (?). If so, should it not just return 0 as the answer? As expected? Regardless of the condition ordering, the loop wouldn’t execute and the program’s procedure should be the same?

Please don’t show pictures of code and messages - cut and paste them.

It looks like there is an issue with the index. Why not log that out and see what is happening in each case.

vec is a vector, not an array: an array is something different and it would be incredibly confusing if the variable vec referred to an array (vectors are containers that grow dynamically, arrays are fixed size)

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.