C++ Program to Add Two Numbers Using Functions

In this post, we will learn how to add two numbers using functions in C++ Programming language.

In the previous post, we have seen how to add two numbers using the standard method. Here, we will use an user-defined function to find the sum of two numbers.

So, without further ado, let’s begin this tutorial.

C++ Program to Add Two Numbers Using Functions

// C++ Program to Add Two Numbers Using Functions
#include <iostream>
using namespace std;

int addTwo(int x, int y);

int main(){
    int a, b, sum;
    
    // Asking for input
    cout << "Enter the first number: ";
    cin >> a;
    cout << "Enter the second number: ";
    cin >> b;
    
    // Calling out user-defined function 
    sum = addTwo(a, b);
    
    // Displaying output
    cout << "Sum of " << a << " and " << b << " is: " << sum << endl;
    return 0;
}

int addTwo(int x, int y){
    return (x + y);
}

Output

Enter the first number: 53
Enter the second number: 64
Sum of 53 and 64 is: 117

How Does This Program Work ?

    int a, b, sum;

In this program, we have declared three integer data type variables named a, b and sum.

    // Asking for input
    cout << "Enter the first number: ";
    cin >> a;
    cout << "Enter the second number: ";
    cin >> b;

The user is asked to enter two numbers. These numbers get stored in the a and b named variables.

    // Calling out user-defined function 
    sum = addTwo(a, b);

Now, we call out the user-defined function named addTwo() to find the sum of two numbers.

int addTwo(int x, int y){
    return (x + y);
}

In this program, we have defined an user-defined function named addTwo which passes two numbers as an argument and returns the sum of those two numbers.

    // Displaying output
    cout << "Sum of " << a << " and " << b << " is: " << sum << endl;

The sum of two numbers is displayed on the screen using the cout statement.

Conclusion

I hope after going through this post, you understand how to add two numbers using functions in C++ Programming language.

If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to assist you.

Also Read:

Leave a Comment

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