Skip to study material
← Question index

QUESTION 08 · Selection

Explain nested if statements with an example.

5 marks

Answer in brief

A nested if statement places one decision inside another decision. It is useful when a second test is needed only after a first test.

Syntax

if (condition1) {
    if (condition2) {
        /* both conditions true */
    } else {
        /* first true, second false */
    }
} else {
    /* first condition false */
}

Example: largest of three values

First compare a with b. If a >= b, compare a with c; the larger of a and c is the maximum. Otherwise, b is larger than a, so compare b with c. This arrangement checks only the part needed for the selected path.

Worked case

For a = 12, b = 7 and c = 20, a >= b is true. The inner test a >= c is false. Therefore c, which is 20, is selected. For equal maximum values, using >= still selects a correct maximum value.

Matching else

Without braces, an else belongs to the nearest earlier unmatched if. Indentation alone does not change this rule. Braces are the safest way to express the intended nesting. Very deep nesting can be difficult to read; consider an else-if ladder or a simpler condition when suitable.

Complexity

The maximum-of-three example makes a fixed number of comparisons and uses a fixed number of variables. Its time and auxiliary space are both O(1). The result does not require sorting the three numbers.

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int a = 12, b = 7, c = 20, maximum;
    if (a >= b) {
        if (a >= c) { maximum = a; }
        else { maximum = c; }
    } else {
        if (b >= c) { maximum = b; }
        else { maximum = c; }
    }
    printf("Maximum = %d\n", maximum);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Maximum = 20

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 →