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:

  1. #include <iostream>: Includes the input-output stream library, allowing input and output operations.

  2. using namespace std;: This line allows elements of the standard C++ library (like cout and endl) to be used without the std:: prefix.

  3. int sum(int a, int b) {...}: Defines a function named sum that takes two integer parameters a and b and returns their sum.

  4. int main() {...}: The main function where the program starts its execution.

  5. int num1 = 5; and int num2 = 3;: Declaration and initialization of two integer variables num1 and num2 with values 5 and 3 respectively.

  6. int result = sum(num1, num2);: Calls the sum function with num1 and num2 as arguments and assigns the returned sum to the result variable.

  7. cout << "The sum of " << num1 << " and " << num2 << " is: " << result << endl;: Outputs the text "The sum of " followed by the values of num1 and num2, the text " is: ", and finally the value of result. endl is used to insert a newline after the output.

  8. return 0;: Indicates successful termination of the main function.