8. User defined functions
C++ allows programmer to define their own function.
A user-defined function groups code to perform a specific task and that group of
code is given a name(identifier).
When the function gets called from any part of program, it all executes the codes
defined in the body of function.
Presented by TA. Nada Kamel
10. Example 1:
void display_welcome_message(string name)
{
// body of the function
cout << “Hello, ” << name << endl;
}
Example 2:
int maximum(int num1, int num2)
{
int result; // local variable declaration
if(num1 > num2)
result = num1;
else
result = num2;
return result;
}
11. Function prototype (declaration)
Function Prototype MUST be written before the main() function.
return_type function_name( parameters list );
Example:
int max(int, int); (OR) int max(int num1, int num2);
Note: It is not necessary to define prototype if user-defined function exists
before main() function.
Presented by TA. Nada Kamel
12. Function Call
To call a function, you simply need to pass the required parameters
along with function name.
If function returns a value, then you can store the returned value in a
variable.
Presented by TA. Nada Kamel
14. Example
Write a C++ program to add two integers.
Make a function add() to add integers and display sum in main() function.
Presented by TA. Nada Kamel
15. #include <iostream>
using namespace std;
// Function prototype (declaration)
int add(int, int);
int main() {
int num1, num2, sum;
cout << "Enter two numbers to add: ";
cin >> num1 >> num2;
// Function call
sum = add(num1, num2);
cout << "Sum = " << sum << endl;
return 0;
}
// Function definition
int add(int a, int b) {
int add;
add = a + b;
// Return statement
return add;
}
17. Problem
Write a C++ function that takes a positive integer number and
returns its factorial.
Mathematically, factorial of an integer number n is referred to as
n! and defined as follows:
n! = n x (n-1) x (n-2) x ...... x 3 x 2 x1 for n > 1, and 0! = 1
Presented by TA. Nada Kamel