In this example, you will write a c++ program for the addition of two numbers, for that you will take two integer inputs from the user and add those two numbers.
#include <iostream>
using namespace std;
int main() {
int number1, number2, sum;
cout << "Enter two number: ";
cin >> number1 >> number2;
// after add number1 and number2 stored them in variabe sum
sum = number1 + number2;
cout << number1 << " + " << number2 << " = " << sum;
return 0;
}
Enter two number: 10 15 10 + 15 = 25
Now look at the explain the above program step by step,
number1
and number2
, and sum
.cout
method.cin
method and stored the number in variables number1 and number2.sum
.In this program, you will get the same output as shown in the above program only difference here is you will perform the addition of two numbers by using function
.
#include <iostream>
using namespace std;
int addNumber(int num1, int num2)
{
return (num1 + num2);
}
int main() {
int number1, number2, sum;
cout << "Enter two number: ";
cin >> number1 >> number2;
// call the addNumber function and store the result in a sum
sum = addNumber(number1, number2);
cout << number1 << " + " << number2 << " = " << sum;
return 0;
}
Enter two number: 10 15 10 + 15 = 25
In this program, the output will be the same as above, the only new thing here is you will add numbers with the help of a recursive function.
#include <iostream>
using namespace std;
int addNumber(int num1, int num2)
{
if(num2 == 0)
return num1;
else
return (1 + addNumber(num1, num2 - 1));
}
int main() {
int number1, number2, sum;
cout << "Enter two number: ";
cin >> number1 >> number2;
// call the addNumber function
sum = addNumber(number1, number2);
cout << number1 << " + " << number2 << " = " << sum;
return 0;
}