
395 views
Add two Numbers using Function in C++
To add two numbers using a function in C++, you can create a simple function that takes two parameters (the numbers to be added) and returns their sum. Here’s an example:
C++
#include <iostream>
// Function to add two numbers
int addNumbers(int num1, int num2) {
return num1 + num2;
}
int main() {
int number1, number2;
// Get user input for the first number
std::cout << "Enter the first number: ";
std::cin >> number1;
// Get user input for the second number
std::cout << "Enter the second number: ";
std::cin >> number2;
// Call the addNumbers function and store the result
int sum = addNumbers(number1, number2);
// Display the result
std::cout << "Sum: " << sum << std::endl;
return 0;
}In this program:
- We define a function called
addNumbersthat takes two integer parameters (num1andnum2) and returns their sum using the+operator. - In the
mainfunction, we declare two integer variables,number1andnumber2, to store the user’s input. - We use
std::cinto get input from the user for bothnumber1andnumber2. - We call the
addNumbersfunction withnumber1andnumber2as arguments and store the result in the variablesum. - Finally, we use
std::coutto display the sum.
When you run this program, it will prompt you to enter two numbers, and then it will calculate and display their sum.