Small Steps III — Thinking with Programs
Handling the not-found case
Handle the case when a value is not found.
What you will learn
A search can succeed or fail. The program should distinguish and report both cases.
Try it
Example · example2.cpp
void small_main()
{
Array<int> numbers = {7, 2, 9, 4, 5};
int value = input_int("Find: ");
int index = -1;
for (int i = 0; i < numbers.length(); i = i + 1)
if (numbers[i] == value)
{
index = i;
break;
}
if (index == -1)
print("Not found");
else
print("Found at ", index);
}
Entering 9 in the console produces Found at 2; entering 8 produces Not found.
Here, break ends only the search loop, and the following if prints the result. Distinguish this from return, which ends the whole function.
Exercise
Use a linear search to find and print the first position of the character 'a' in a String. Use -1 if absent.
Exercise starter · exercise2_starter.cpp
void small_main()
{
String text = "Small C++";
int index = -1;
// find the first 'a'.
print(index);
}
Hint
String also supports length and [], so this is almost the same as searching an Array.
show solution
void small_main()
{
String text = "Small C++";
int index = -1;
for (int i = 0; i < text.length(); i = i + 1)
if (text[i] == 'a')
{
index = i;
break;
}
print(index);
}