Skip to study material
← Question index

QUESTION 30 · Worked algorithms

Draw and explain a flowchart to determine whether an integer is even or odd.

5 marks

Answer in brief

An integer is even if it is divisible by 2 without a remainder. Otherwise it is odd.

Algorithm

  1. Read n: Accept an integer.
  2. Test n % 2 == 0: The % operator gives the remainder of integer division.
  3. Print Even: Use this result when the remainder is zero.
  4. Print Odd: Use this result when the remainder is not zero.
  5. End: Only one of the two results is printed.

Explanation

The condition directly checks divisibility by 2. If the remainder is zero, n can be written as 2 multiplied by an integer. In a flowchart, place this condition inside a decision diamond. Label the true branch Yes and the false branch No. Each branch displays its result and reaches End.

Examples

For n = 8, 8 % 2 is 0, so the output is Even. For n = 7, the remainder is 1, so the output is Odd. Zero is even because 0 = 2 × 0. For n = −3, C gives a remainder of −1; it is non-zero, so the number is still correctly reported as Odd.

Important point

Do not test oddness only by n % 2 == 1 when negative inputs are allowed. A negative odd number can give remainder −1. Testing for a zero remainder and using the other branch for Odd handles both signs. The program also checks that reading the input succeeds before using n. Input values must fit int.

Time and space complexity

One remainder and one comparison are enough. There is no loop, so time is O(1). Only a fixed number of variables is required, giving O(1) extra space.

Reference table

↔ Scroll horizontally on a small screen
Boundary checks
CaseExpected behaviour
n = 0Even.
n = −4Even.
n = −3Odd.
Non-numeric inputReject before using n.

Diagram or flowchart

Read n, test whether n modulo two is zero, print the chosen classification and end.
One decision: 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; }
    puts(n % 2 == 0 ? "Even" : "Odd");
    return 0;
}

Sample input and output

Input

-3

Output

Odd

Key points

  • An integer is even when its remainder on division by 2 is zero; otherwise it is odd.
  • Test for a zero remainder, not for remainder equal to one.

Related exam questions

Topic matches from the supplied JNTUH papers. Marks below are the printed allocations for those questions.

  • September 2023 · Q1(a) · 2 marks

    Draw a flowchart to find whether a number is even or odd.

    Paper P09 · page 1
View all matching exam references →