C++ Program For Addition of Two Numbers

In this post, we will develop the C++ program for the addition of two numbers. First, we will develop a simple program for the addition of two numbers in C++, and then we will develop a C++ program for the addition of two numbers using functions.

To add two numbers we have to declare two variables. The data type of these variables can be int, float, or double type. Since using double data type we can store both integer and floating-point numbers so we will take double data type. We can take input directly (hardcode) or we can ask the end-user for the input.

// C++ program to add two numbers
#include<iostream>
using namespace std;
int main()
{
    // declare two variables to store numbers
    double num1, num2;
    // declare variable to store sum value
    double sum;
    
    // ask input from end-user
    cout << "Enter Two Numbers : ";
    cin >> num1 >> num2;
    
    // calculate sum value
    sum = num1 + num2;
    
    // display result
    cout << "Sum = " << sum << endl;

    return 0;
}

Output:-

Enter Two Numbers: 12 13
Sum = 25

C++ Program for Addition of Two Numbers Using Functions

Here we will write a C++ program for the addition of two numbers using functions. For this develop a function add() to calculate the addition of two integers and display sum value in the main() function.

A function is a block of code that performs a specific task. For example, the main is function and every program execution starts from main function in C++ programming.

// C++ Program for Addition of Two Numbers Using Functions
#include<iostream>
using namespace std;

// function prototype (declaration)
double add(double, double);

// main method
int main()
{
  // declare variables
  double num1, num2, sum;

  // take input from end-user
  cout << "Enter Two Numbers : ";
  cin >> num1 >> num2;
  
  // calculate sum value
  // function call
  sum = add (num1, num2);
  
  // display sum value
  cout << "Sum = " << sum << endl;
  
  return 0;
}

// function definition
double add(double x, double y)
{
  double z;
  z = x + y;
  //return statement
  return z;
}

Output:-

Enter Two Numbers: 45.8 12.5
Sum = 58.3

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Learn More C++ Programming Examples,

Leave a Comment

Your email address will not be published. Required fields are marked *