In this article, we will learn how to in C++ add two numbers by value or by reference by using functions. We will pass the numbers to a function and that function will do the logic of addition in C++ to give the results. We will learn this by using both C++ addition using call by value function and also C++ addition using call by reference.
- add two numbers by value using the function
- add two numbers using call by Reference
1. C++ Program to add two numbers by value using function
In this example, we are doing the addition of two numbers by using a function. We have written the addition logic to a function and when the user is providing the numbers to add, we are passing those numbers to the function. This function performs the addition and returns the results back to the calling function.
#include <iostream>
using namespace std;
int addition(int a,int b);
int addition(int a,int b)
{
int add = a + b;
return add;
}
int main()
{
int num1,num2;
int sum = 0;
cout<<"Please enter the first number: ";
cin>>num1;
cout<<"Please enter the second number: ";
cin>>num2;
sum = addition(num1,num2);
cout<<"The sum of Given numbers is: "<< sum <<endl;
return 0;
}
Output
Please enter the first number: 6
Please enter the second number: 7
The sum of Given numbers is: 13
- 6 ways to Reverse Array in C++
- How to Find Max Value in C++ Array
- How to Find Minimum Value in C++ Array
- Different ways to Declare arrays in C++
- Create Pointer arrays in C++ dynamically
- Different ways to Declare arrays of strings in C++
- Loop through Array in C++
- 6 Ways to Find Size of Array in C++
- How to return an Array From a Function in C++
2. C++ Program to add two numbers using call by Reference
In this example, we are going to use the function and call by reference technique to add two numbers. We will provide the numbers to the function as arguments, this function will do the logic of addition for us. Once the addition is done it will provide us the result in the same argument that we will pass to it as reference.
#include<iostream>
using namespace std;
void addition(int No1, int No2, int *result);
void addition(int No1, int No2, int *result)
{
*result = No1 + No2;
}
int main()
{
int num1,num2;
int sum = 0;
cout<<"Please enter the first number: ";
cin>>num1;
cout<<"Please enter the second number: ";
cin>>num2;
addition(num1, num2, &sum);
cout<<"The sum of Given numbers is: "<< sum <<endl;
return 0;
}
Output:
Please enter the first number: 8
Please enter the second number: 9
The sum of Given numbers is: 17