C++ add two numbers using the function
Here we will learn how to add two numbers by creating function in C++.
Let’s learn this with help of example.
Code: -
#include <iostream>
using namespace std;
int add_two_no(int a, int b);
int main(){
int first_num, second_num, sum;
cout << "Enter the first number: ";
cin >> first_num;
cout << "Enter the second number: ";
cin >> second_num;
sum = add_two_no(first_num, second_num);
cout << "Sum of " << first_num << " and " << second_num << " is: " << sum << endl;
return 0;
}
int add_two_no(int a, int b){
return (a + b);
}
Output: -
Explanation:-
In the above code, three integer variables are named first_num,second_num, and sum.
After that, the user is asked to enter inputs, and it is stored in variables first_num and second_num.
After that user-defined function is created named add_two_no for calculating the addition of two numbers and is called for the same purpose.
The user-defined function named add_two_no passes two numbers as an argument/parameter and returns the sum of the two numbers.
And in the last is displayed using cout statement.