Confused About For Loop and Boolean Logic in Code

0
5
Asked By CodeExplorer27 On

Hey everyone! I'm diving into some code and I'm a bit puzzled about how the for loop works with the boolean variable. I see that there's an if statement inside the loop that checks if a country is in a vector, which sets the boolean to true if found, and then it breaks out of the loop. After that, there's another if statement that checks the boolean, and since it's not false anymore, the program finishes.

What I'm stuck on is—since the boolean starts as false, isn't the for loop supposed to run as long as the loop's conditions are met and 'foundCountry' turns true when it finds a match? Shouldn't it be checking for foundCountry == false instead? Here's a snippet from my code for clarity:

// Find country's index and average TV time
foundCountry = false;
for (i = 0; (i < ctryNames.size()) && (!foundCountry); ++i) {
if (ctryNames.at(i) == userCountry) {
foundCountry = true;
cout << "People in " << userCountry << " watch ";
cout << ctryMins.at(i) << " mins of TV daily." << endl;
}
}
if (!foundCountry) {
cout << "Country not found; try again." << endl;
}

return 0;

3 Answers

Answered By LogicGuru44 On

Yep, `foundCountry == false` works the same way as `!foundCountry`. Don’t worry; sometimes programming semantics can be a bit convoluted!

CodeExplorer27 -

Oh, I had thought that `!foundCountry` was changing the value stored in the variable. Thanks for explaining. Sorry for confusing wording lol.

Answered By SyntaxWhiz On

This is a common confusion with boolean logic in programming. Remember that only increment/decrement operators like `i++`, `++i`, etc., will change variable values. Conditions like `!foundCountry` just check the current state.

Answered By TechSavvy99 On

The `!variable` syntax is equivalent to `variable == false`. So, your understanding is on track! The loop keeps running as long as `foundCountry` is false. But when you set it to true inside the loop, the next iteration won't happen because `!foundCountry` evaluates to false. That's why it breaks out of the loop when the country is found.

CodeExplorer27 -

Oh, I had thought that `!foundCountry` was changing the value stored in the variable. Thanks for explaining, I appreciate it.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.