It isused to test a series of conditions sequentially, executing the code for the first true condition. A condition is checked only if all previous ones are false.
Once a condition is true, its code block executes, and the ladder ends.
Output
B
Explanation: The program checks the value of marks and assigns a grade based on predefined ranges. It checks from highest to lowest, printing the grade based on the conditions met, or "F" if none are met.
Syntax of Complete if, else if Ladder
where,
condition1, condition2: Contitions that are to be tested.
statements 1, statements 2: Code block corresponding to each condition.
else body: code block to be executed if none of the condition evaluate to true.
Working of if, else if Ladder
The working of if else if ladder can be understood using the following flowchart:
If Condition 1 evaluates to true, Statement 1 is executed, and the rest of the else if and else conditions are skipped.
If Condition 1 is false, Condition 2 is evaluated.
If Condition 2 evaluates to true, Statement 2 is executed, and the else block is skipped.
If Condition 2 is also false, the Else Body is executed.
After completing the if-else-if ladder, the statement just below the if are executed.
Check if a number is positive, negative or 0
Output
Number = 10
Positive.
Explanation: The if-else if ladder checks whether the number is greater than zero (positive), less than zero (negative), or exactly zero. Based on the result, the corresponding message is printed.
Print the day name using day number
Output
Day Number: 3
Day Name: Wednesday
Explanation: This program checks the value of day and prints the corresponding day of the week. If the value of day is not between 1 and 7, it prints "Invalid day."