How to Return the sum of two parameters in C++ ?
To return the sum of two parameters in C++, you can define a function that takes two parameters and returns their sum. Here are two methods to do it:
Method 1: Using a Function
#include <iostream>
using namespace std;
int sum(int a, int b) {
return a + b;
}
int main() {
int x = 5, y = 10;
int result = sum(x, y);
cout << "The sum of " << x << " and " << y << " is " << result << endl;
return 0;
}
Output:
The sum of 5 and 10 is 15
In this method, we define a function sum
that takes two integer parameters a
and b
and returns their sum. In the main
function, we call the sum
function with two integer arguments x
and y
and store the result in a variable result
. Finally, we print the result using the cout
statement.
Method 2: Using a Lambda Function
#include <iostream>
using namespace std;
int main() {
int x = 5, y = 10;
auto sum = [](int a, int b) { return a + b; };
int result = sum(x, y);
cout << "The sum of " << x << " and " << y << " is " << result << endl;
return 0;
}
Output:
The sum of 5 and 10 is 15
In this method, we define a lambda function sum
that takes two integer parameters a
and b
and returns their sum. We use the auto
keyword to let the compiler deduce the return type of the lambda function. In the main
function, we call the sum
lambda function with two integer arguments x
and y
and store the result in a variable result
. Finally, we print the result using the cout
statement.