C++ program to add two numbers

In this example, you will write a c++ program for the addition of two numbers, for that you will take two integer inputs from the user and add those two numbers.


#include <iostream>
using namespace std;

int main() {

  int number1, number2, sum;
    
  cout << "Enter two number: ";
  cin >> number1 >> number2;

  // after add number1 and number2 stored them in variabe sum
  sum = number1 + number2;

  cout << number1 << " + " <<  number2 << " = " << sum;     

  return 0;
}
output
Enter two number: 10  15
10 + 15 = 25

Now look at the explain the above program step by step,

  • first, we have declared three variables i.e number1 and number2, and sum.
  • print the message on the screen like "Enter two numbers" you can do that with the help of cout method.
  • take two numbers from the user with the help of cin method and stored the number in variables number1 and number2.
  • add both the number and stored it in a variable sum.
  • now print the value of the sum after performing addition.

C++ program to add two numbers using function

In this program, you will get the same output as shown in the above program only difference here is you will perform the addition of two numbers by using function.


#include <iostream>
using namespace std;

int addNumber(int num1, int num2)
{
    return (num1 + num2);
}

int main() {

  int number1, number2, sum;
    
  cout << "Enter two number: ";
  cin >> number1 >> number2;

  // call the addNumber function and store the result in a sum
  sum = addNumber(number1, number2);
   
  cout << number1 << " + " <<  number2 << " = " << sum;     

  return 0;
}
output
Enter two number: 10   15
10 + 15 = 25

Sum of two numbers in c++ using recursive function

In this program, the output will be the same as above, the only new thing here is you will add numbers with the help of a recursive function.


#include <iostream>
using namespace std;

int addNumber(int num1, int num2)
{
    if(num2 == 0)
        return num1;
    else
        return (1 + addNumber(num1, num2 - 1));
}

int main() {

  int number1, number2, sum;
    
  cout << "Enter two number: ";
  cin >> number1 >> number2;

  // call the addNumber function 
  sum = addNumber(number1, number2);
   
  cout << number1 << " + " <<  number2 << " = " << sum;     

  return 0;
}