Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m having trouble understanding a bool concept in the book. Below is some code

ID: 3587155 • Letter: I

Question

I'm having trouble understanding a bool concept in the book. Below is some code presented in Chapter 8 pg. 458 of Starting Out with C++ From Control Structures Through Objects 8th Edition (the part I'm confused about is in bold):

int searchList(const int list[], int numElems, int value)
{
int index = 0; // Used as a subscript to search array
int position = 1; // To record position of search value
bool found = false; // Flag to indicate if the value was found
while (index < numElems && !found)
{
if (list[index] == value) // If the value is found
{
found = true; // Set the flag
position = index; // Record the value's subscript
}
index++; // Go to the next element
}
return position; // Return the position, or 1
}

My question is why is the while statement checking if "found" is true instead of false? Wouldn't that mean that the while statment would continue even when found is true?

Explanation / Answer

while (index < numElems && !found)

Above while loop runs for following conditions

Note that !found is used that means, it runs when !found is true besides index<numElems.

If !found should be true then found should be false which is not of false(!false).

Given condition can be rewritten to

Hence the loop runs when found is false only.

while (index < numElems && !false)
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote