sum function in c++
#include <iostream>
using namespace std;
int sum(int a, int b) {
return a + b;
}
int main() {
int num1 = 5;
int num2 = 3;
int result = sum(num1, num2);
cout << "The sum of " << num1 << " and " << num2 << " is: " << result << endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the input-output stream library, allowing input and output operations.using namespace std;
: This line allows elements of the standard C++ library (likecout
andendl
) to be used without thestd::
prefix.int sum(int a, int b) {...}
: Defines a function namedsum
that takes two integer parametersa
andb
and returns their sum.int main() {...}
: The main function where the program starts its execution.int num1 = 5;
andint num2 = 3;
: Declaration and initialization of two integer variablesnum1
andnum2
with values 5 and 3 respectively.int result = sum(num1, num2);
: Calls thesum
function withnum1
andnum2
as arguments and assigns the returned sum to theresult
variable.cout << "The sum of " << num1 << " and " << num2 << " is: " << result << endl;
: Outputs the text "The sum of " followed by the values ofnum1
andnum2
, the text " is: ", and finally the value ofresult
.endl
is used to insert a newline after the output.return 0;
: Indicates successful termination of themain
function.