Did you know that loop statements may have an else clause?
Well, it turns out that they can be used!
-
else
clause will be executed when the loop completes through all of the iterations with for loop and when the condition becomes false with while loop.
Output:
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Treasure not found :(
- But
else
clause will not be executed when the loop is terminated by a break statement.
Output:
Searching...
Searching...
Searching...
Searching...
Found the treasure
Top comments (0)