C PROGRAM • INPUT, OUTPUT & OPERATORS

Add Two Integers

Read two integers, add them and inspect how the result variable receives the calculated value.

Beginnerscanf()AdditionVariables

PROBLEM UNDERSTANDING

Input and expected output

Sample input
12 8
Sample output
Enter two integers: 12 8
Sum = 20

C PROGRAM

Complete program

add-two-numbers.c
#include <stdio.h>

int main(void)
{
    int first, second, sum;
    printf("Enter two integers: " );
    scanf("%d %d", &first, &second);
    sum = first + second;
    printf("Sum = %d\n", sum);
    return 0;
}

INTERACTIVE LEARNING

Debug this program line by line

Watch the active line, variables and output.

CURRENT STEP

Select Start to trace this program.

VARIABLES

ScopeNameValue
Not started

CALL STACK

main()

PROGRAM OUTPUT

Waiting to run…
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read two integers.
  2. Add the values and store the result in sum.
  3. Print sum.

scanf() stores the entered integers in first and second. The + operator produces a new value, which is assigned to sum before printf() displays it.

EFFICIENCY

Time and space complexity

Time complexity

O(1)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Forgetting & before variables in scanf().

Check this

Using the wrong format specifier for an integer.