Small Steps I — Creating with Text and Numbers
Doing something else when a condition is false
Print Open when the password equals 1234 and Locked otherwise. Test with 1111.
What you will learn
else holds the instructions to run when the if condition is false. It chooses one of two branches.
Try it
Example · example.cpp
void small_main()
{
int answer = 4;
if (answer == 4)
{
print("Correct");
}
else
{
print("Try again");
}
}
Use == to compare for equality. It is different from =, which assigns a value. != compares whether values differ. Changing answer to 5 runs only the else branch.
Expected output:
Correct
Exercise
Print Open when the password equals 1234 and Locked otherwise. Test with 1111.
Exercise starter · exercise_starter.cpp
void small_main()
{
int answer = 4;
if (answer == 4)
{
print("Correct");
}
else
{
print("Try again");
}
}
Hint
Change the parts of the example that you need.
show solution
void small_main()
{
int password = 1111;
if (password == 1234)
{
print("Open");
}
else
{
print("Locked");
}
}