Skip to study material
← Question index

QUESTION 06 · Selection

Explain if-else with a C program to test whether an integer is even or odd.

5 marks

Answer in brief

The if-else statement chooses between two alternatives based on a condition.

Syntax

if (condition) {
    /* true branch */
} else {
    /* false branch */
}

Algorithm

  1. Read an integer n.
  2. If n % 2 equals zero, print Even.
  3. Otherwise, print Odd. End the program.

Explanation

The % operator finds the remainder after integer division. A number is even when division by 2 leaves remainder zero. For n = 8, the condition is true and Even is printed. For n = 7, the condition is false and Odd is printed. Zero is even. Negative even numbers also have remainder zero, so the same condition works for them.

Important points

The else branch is optional in a simple if but necessary when a different action is required for a false condition. Place braces around the branches to make their boundaries clear. There is no condition after else. A later statement outside both branches executes after either branch finishes, unless a jump leaves that path.

Time and space complexity

The program uses one remainder calculation and one decision, regardless of the integer value. For the fixed-width integer model used here, time is O(1). Only a fixed number of variables is used, so auxiliary space is O(1).

Flowchart

Control flow for if-else with labelled true and false paths.
Explain if-else with a C program to test whether an integer is even or odd. · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int n;
    if (scanf("%d", &n) != 1) {
        puts("Invalid input");
        return 1;
    }
    if (n % 2 == 0) {
        puts("Even");
    } else {
        puts("Odd");
    }
    return 0;
}

Sample input and output

Input

7

Output

Odd

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 →