Part 4 of 5 in Reading input and writing output  

Add two numbers by admin2

Problem statement

Given two numbers, add them and print their sum


Input contains two numbers between 1 and 100, separated by a space


Print the sum of the 2 numbers

Sample Input
1 2
Sample Output

First we declare the two numbers and take them as input from the user.

//Declare the two numbers
int num1, num2;
//Take input from the user
cin >> num1 >> num2;

Then we calculate the sum using the + operator and store it in a variable. The + operator is a binary operator that takes two operands and returns the sum of these two.

//Calculate the sum
int sum = (num1 + num2);

Then we print the sum we just calculated.

//print the sum
cout << sum << endl;

You can also directly print the sum without storing it in a variable pke this.

cout << (num1 + num2) << endl;

In C, we can use scanf("%d", &num1) to read in an integer.

In Java, we can use Scanner.nextInt() to read an integer.

In C#, we will need to read the entire line, split it by whitespace and then parse each number individually.

string[] numbers = Console.ReadLine().Split();
Console.Write(Int32.parse(numbers[0]) + Int32.parse(numbers[1]));

editorial written by i_coder


using namespace std;
int main()
    //Declare the two numbers
    int num1;
    int num2;
    //Take input from the user
    cin >> num1 >> num2;
    //Calculate the sum
    int sum = (num1 + num2);
    //Print the sum
    cout << sum << endl;

featured solution by i_coder

To try out your code

Sign in

Sign up