Skip to study material
← Question index

QUESTION 32 · Worked algorithms

Develop an algorithm and flowchart to find the sum of two numbers.

5 marks

Answer in brief

To find the sum of two numbers, read both values, add them and display the result.

Input and output

Inputs: two numbers a and b. Output: their sum. Choose a numeric type that can hold the allowed values and their result. Use an integer type for whole-number examples or a floating type when fractional inputs are required.

Algorithm

  1. Start: Begin the solution.
  2. Read a and b: Obtain both input values.
  3. Calculate sum: Set sum = a + b.
  4. Display sum: Show the calculated value.
  5. Stop: The required result has been produced.

Pseudocode

READ a, b
sum ← a + b
OUTPUT sum

Example

Let a = 12 and b = 15. After reading the inputs, the addition gives 27. Store 27 in sum and display it. For a = −5 and b = 5, the sum is zero. No decision or repeated calculation is needed for these stated examples.

Flowchart and program

The flowchart contains Start, an input symbol, a processing rectangle for addition, an output symbol and End. The supplied program uses fixed small values so that the output can be checked easily. A program that accepts arbitrary user values must also check input conversion and ensure that the result fits the chosen type. A correct mathematical sum can still be too large for int.

Time and space complexity

The algorithm always performs one addition. Therefore its time is O(1). A fixed number of variables is used, so extra space is O(1). Adding n values would require a repeated step and would take O(n) time.

Reference table

↔ Scroll horizontally on a small screen
Boundary checks
CaseExpected behaviour
0 and 00.
−5 and 50.
12 and 1527.
Unrepresentable signed sumMust be prevented in a general input implementation.

Diagram or flowchart

Start, read two numbers, compute their sum, print the result and end.
Sequence for adding two values · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int a = 12, b = 15;
    int sum = a + b;
    printf("Sum = %d\n", sum);
    return 0;
}

Sample input and output

This example uses values already written in the program.

Output

Sum = 27

Key points

  • Read the two values, add them using a suitable numeric type, then display the result.
  • The chosen C type must be able to represent the result.

Related exam questions

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

  • September 2023 · Q1(j) · 3 marks

    Write an algorithm to find the sum of two numbers.

    Paper P09 · page 1
View all matching exam references →