CC103 6 Functions
CC103 6 Functions
C++ Functions
Reychelle G. Nabong, MSIT
Instructor
C++ Functions
Dividing a complex problem into smaller chunks makes our program easy to
understand and reusable.
There are two types of function:
• Standard Library Functions: Predefined in C++
• User-defined Function: Created by users
C++ User-defined Function
• Functions make the code reusable. We can declare them once and
use them multiple times.
• Functions make the program easier as each small task is divided
into a function.
• Functions increase readability.
The C++ Functions
A C++ function or a subprogram is simply a chunk of C++ code that
has:
A descriptive function name: Examples
computeTaxes to compute the taxes for an employee
isPrime to check whether or not a number is a prime number
Usage:
FUNCTION BODY.
The statements to be executed inside the function
showHeader(); (inside {} “curly braces”)
The C++ User-Defined Functions
NON-VALUE RETURNING FUNCTION (sample with parameter)
void greetEmployee(string employeename) {
cout << “Student Information System” << endl;
cout << “Welcome ” << employeename;
}
Usage:
string employee = “Kim Seokjin”;
greetEmployee(employee);
Output:
Student Information System
Welcome Kim Seokjin
The C++ User-Defined Functions
FUNCTION PARAMETERS. A function may don’t have or can have 1
or more parameters to perform its task.
void employeeTax(string employeename, double salary, double tax_percent=0.12) {
cout << “Employee Name: ” << employeename << endl;
cout << “Salary: ” << salary << endl;
cout << “Tax Percent: ” << tax_percent << endl; OUTPUT:
double tax = salary * tax_percent;
cout << “Tax: ” << tax << endl; Employee Name: JIN
Salary: 30000
} Tax Percent: 0.12
Usage: Tax: 3600
employeeTax(“JIN”, 30000.00);
Employee Name: JUNGKOOK
employeeTax(“JUNGKOOK”, 50000.00, 0.15); Salary: 50000
Tax Percent: 0.15
Tax: 7500
The C++ User-Defined Functions
FUNCTION PARAMETERS. A function may don’t have or can have 1
or more parameters to perform its task.
Required parameters must be placed at the start and the optional parameters must be placed at the
ends part
CORRECT DECLARATION:
WRONG DECLARATION:
void employeeTax(double tax_percent=0.12, string employeename, double salary)
The C++ User-Defined Functions
Incorrect Usage
Actual Declaration.
Placed after int main
driver.
Laboratory Exercise
Create a C++ program with the
following specification: