Skip to study material
← Question index

QUESTION 10 · Selection

Explain the else-if ladder with a grade-classification example.

5 marks

Answer in brief

An else-if ladder chooses one action from several alternatives by checking conditions from top to bottom.

Syntax

if (condition1) {
    /* action 1 */
} else if (condition2) {
    /* action 2 */
} else {
    /* remaining cases */
}

Working

  1. Check the first condition. If true, execute its branch and leave the ladder.
  2. Otherwise, check the next condition. Continue until a true condition is found.
  3. If no condition is true, execute the final else when it is present.

Example: grade ranges

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.

Why order matters

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.

Complexity

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).

C program and output

/* 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;
}

Sample input and output

This example uses values already written in the program.

Output

Grade B

Related exam questions

Related questions in the selection category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q3(a) · 5 marks

    Discuss decision-making statements with an example.

    Paper P02 · page 1
  • June 2022 · Q2(b) · 8 marks

    Illustrate forms of if statements with syntax and examples.

    Paper P03 · page 1

View this category in the exam question bank →