QUESTION 09 · Selection
What is an else-if ladder?
2 marksAnswer
It is a sequence of linked if-else decisions that tests conditions in order.
- Only the first true branch is executed.
- A final else handles values that fail all earlier tests.
QUESTION 09 · Selection
It is a sequence of linked if-else decisions that tests conditions in order.
QUESTION 10 · Selection
An else-if ladder chooses one action from several alternatives by checking conditions from top to bottom.
if (condition1) {
/* action 1 */
} else if (condition2) {
/* action 2 */
} else {
/* remaining cases */
}Use marks from 0 to 100. Reject values outside that range first. Then check marks >= 90 for A, marks >= 75 for B, and marks >= 60 for C. Remaining valid marks receive D. These are example grade boundaries, rather than an official institution policy.
For marks = 82, the first grade condition is false and the second is true, so B is printed. Later conditions are skipped. If marks >= 60 were tested first, 95 would incorrectly receive C because that earlier condition would already be true. Place the highest boundary first when conditions are written this way.
With k conditions, at most k tests may be required, giving O(k) time in the general case. This example has a fixed small number of conditions, so its work is O(1) with respect to the input value. Auxiliary space is O(1).
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int marks = 82;
if (marks < 0 || marks > 100) { puts("Invalid marks"); }
else if (marks >= 90) { puts("Grade A"); }
else if (marks >= 75) { puts("Grade B"); }
else if (marks >= 60) { puts("Grade C"); }
else { puts("Grade D"); }
return 0;
}This example uses values already written in the program.
Grade BRelated questions in the selection category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.
Discuss decision-making statements with an example.
Paper P02 · page 1Illustrate forms of if statements with syntax and examples.
Paper P03 · page 1