Learn
Conditional Statements
Else If Statements
In programming, there are situations where we need to evaluate multiple conditions and execute different blocks of code depending on the outcome. The if
statement alone might not always be sufficient for these scenarios. In such cases, we can make use of the else if
statement to handle additional conditions.
The else if
statement allows us to chain multiple conditions together and provides an alternative block of code to be executed if the previous condition(s) evaluate to false. This allows for more flexibility in our program's logic.
Let's take a look at the syntax of the else if
statement:
It's important to note that else if
statements are evaluated in order from top to bottom. Once a condition evaluates to true, the corresponding block of code is executed and the rest of the else if
statements are skipped. If none of the conditions evaluate to true, the code within the else
block is executed as a fallback.
Example:
Let's say we are building a program that determines the grade of a student based on their score. We can use else if
statements to handle different score ranges and assign the corresponding grade:
In this example, the program checks the score against different conditions and assigns the appropriate grade based on the score. If the score is 85, the output would be "Your grade is B".
Instructions
Add an else if
statement that checks if num
is greater than 10
.
If num
is greater than 10
, assign the string "Large number"
to a variable named result
.
Else if num
is greater than 5
, assign the string "Medium number"
to a variable named result
Else, assign the string "Small number"
to a variable named result
Print the value of result
to the console.
Sign up to start coding
Already have an account?
Sign In