C++ Program to Add Two Numbers

  • Write a program in C++ to add two numbers.
  • Write a C++ program to find sum of two numbers using a function.
  • How to add two integers in C++ using + operator.

To find sum of two numbers in C++, we will first take two numbers as input from user using cin and store them in two local variable. Now, we will add two input numbers using addition operator ('+') and store the sum in third variable. Finally, we will print the sum of two numbers on screen using cout.

C++ program to add two numbers using + operator

/*
* C++ Program to add two numbers using + operator
*/
#include <iostream>

using namespace std;

int main() {
    float num1, num2, sum;
    
    // Taking input from user
    cout << "Enter Two Numbers\n";
    cin >> num1 >> num2;
    
    // Adding two input numbers
    sum = num1 + num2;
    
    // Printing output
    cout << "Sum of "<< num1 << " and " << num2 << " is " << sum;
    return 0;
}
Output
Enter Two Numbers
4 3.5
Sum of 4 and 3.5 is 7.5

C++ program to find sum of two numbers using function

In this program, we will use a user defined function float getSum(float a, float b) which takes two floating point number as input and returns the sum of input parameters.


/*
* C++ Program to add two numbers using function
*/
#include <iostream>

using namespace std;

// Function to add two numbers
float getSum(float a, float b){
 return a + b;
}

int main() {
    float num1, num2, sum;
    
    // Taking input from user
    cout << "Enter Two Numbers\n";
    cin >> num1 >> num2;
    
    // Adding two input numbers by calling getSum function
    sum = getSum(num1, num2);
    
    // Printing output
    cout << "Sum of "<< num1 << " and " << num2 << " is " << sum;
    return 0;
}
Output
Enter Two Numbers
3.2 4.5
Sum of 3.2 and 4.5 is 7.7

Related Topics
C++ Program to Find Sum of Natural Numbers
C++ Program to Find Quotient and Remainder
C++ Program to Check Whether Number is Even or Odd
C++ Program to Find Product of Two Numbers
C++ Program to Find Largest of Three Numbers
C++ Program to Find Factorial of a Number
C++ Program to Check Leap Year
C++ Program to Find GCD of Two Numbers
C++ Program to Find the Length of a String
List of all C++ programs