Linear Search Exercice
Linear search
Solution with while loop
string[] persons = ["Juliana", "Logan", "Gabriela", "Valentina", "Lelio", "Linda"];
Console.Write("Name => ");
string name = Console.ReadLine();
int position = 0;
while (position < persons.Length && name != persons[position])
{
position++;
}
if (position == persons.Length)
{
Console.WriteLine($"Not found: no name like '{name}'.");
}
else
{
Console.WriteLine($"Found! Position is {position}.");
}Solution with for loop
string[] persons = ["Juliana", "Logan", "Gabriela", "Valentina", "Lelio", "Linda"];
Console.Write("Insert a name:");
string name = Console.ReadLine();
int position;
bool found = false;
for (position = 0; position < persons.Length; position++)
{
if (persons[position] == name)
{
found = true;
break;
}
}
if (found == false)
{
Console.WriteLine("Not found!");
}
else
{
Console.WriteLine($"Found! position is {position}");
}Note
Exercise: Find Valentina
INPUT What do I receive? Valentina
OUTPUT What do I give back? Position (index)
EXAMPLE Solve one by hand: Valentina => 3
STEPS In plain words, no C#:
1. Ask for a name
2. Define starting position at zero
3. Compare given name to name at current position
4. If given is the same as current position then step and show position
5. If not the same then we go to the next position
6. Compare again
3. I stop when I find a match
4. Show the position
TRACE
| turn | Name | ........ |
| 0 | Juliana | |
| 1 | Logan | |
| 2 | Gabriela | |
| 3 | Valentina | |
EDGE CASES 0? 1? negative? empty? ......................
参与讨论