Small Steps I — Creating with Text and Numbers
Choosing one of three branches
Change number to -2 and check which branch runs.
What you will learn
For three or more choices, connect conditions with else if. They are checked from top to bottom, and only the first matching branch runs.
Try it
Example · example.cpp
void small_main()
{
int number = 0;
if (number > 0)
{
print("Positive");
}
else if (number < 0)
{
print("Negative");
}
else
{
print("Zero");
}
}
0 is neither positive nor negative, so it reaches the final else. Several independent if statements check their conditions separately, so more than one branch may run.
Expected output:
Zero
Exercise
Change number to -2 and check which branch runs.
Exercise starter · exercise_starter.cpp
void small_main()
{
int number = 0;
if (number > 0)
{
print("Positive");
}
else if (number < 0)
{
print("Negative");
}
else
{
print("Zero");
}
}
Hint
Change the parts of the example that you need.
show solution
void small_main()
{
int number = -2;
if (number > 0)
{
print("Positive");
}
else if (number < 0)
{
print("Negative");
}
else
{
print("Zero");
}
}