You are on page 1of 51

FUNCTIONS

PART 1
UCCD1004 Programming Concepts and Practices
Content Overview

Structure of C++ Programs

Statements Control Control


String and
and Structures Structures Functions Structs Pointers
Array
Expressions (Selection) (Iteration)

Input & Pass-by-


Data Types FileIO Classes
Output reference
Introduction
• It is difficult to maintain one whole big piece of program on its
own.

• In order to make codes maintainable, codes need to be


modular.

• Function is just a form/a way to make codes to be modular.


There are many more ways that you will learning in OOP.
Introduction
Introduction
Problem – Book Hotel Room
What Room
How many
Welcome Type? Hotel
todays?
UTAR
Customer A President Room
1. Registration
Receptionist
Deluxe
1 day A Room
1. Book
2. Room
Single
2. Check
3. Room
2 days Out
3. Exit
4. 3 days
4. 4 days
Selection: 23
……………… Selection: 4
Introduction
Problem – Book Hotel Room
Welcome
What Isyou
Thank tofor
Your UTAR
Room Hotel
No?
the stay in our hotel.
Customer B 1. Registration
Please come back again!
Receptionist
2.
RoomBook 88888
No:A Room
3. Check Out
4. Exit

Selection: 3
………………
Introduction
Problem – Book Hotel Room
What
How many
Welcome Room Type? Hotel
todays?
UTAR
Customer C President Room
1. Registration
Receptionist
1Deluxe
1. Book
2. day A Room
Room
2Single
2. Check
3. Room
days Out
3. Exit
4. 3 days
4. 4 days
Selection: 23
……………… Selection: 4
Introduction
Problem – Hotel System
do {
if (/*Registration*/) {
//Statements
//Lines of codes
}
else if (/* Book a room*/) {
//Statements
//Lines of codes
}
else if (/*Check Out*/) {
//Statements
//Lines of codes
}
else {
//Exit
//Lines of codes
}

//Continue to the main menu? Yes or No?


}while(/*repeat the menu if yes*/)
Introduction
Problem – Hotel System
■ What about calculating the total of empty rooms when customer
book the hotel?
■ What about calculating the total of empty rooms when customer
check out?
Introduction
Problem – Book Hotel Room
int main(){
do {
if (/*Registration*/) {
//Statements
Repeat the multiple lines???
//Lines of codes Seriously 2 times!!!
}
else if (/* Book a room*/) {
//Statements
//Lines of codes
…………………………………...
Calculating the total of empty rooms
}
else if (/*Check Out*/) {
//Statements
//Lines of codes
…………………………………. Calculating the total of empty rooms
}
else {
//Exit
//Lines of codes
}

//Continue to the main menu? Yes or No?


}while(/*repeat the menu if yes*/)
}
Introduction
Problem – Hotel System
int main(){
do {
if (/*Registration*/) {
How many lines of codes you
//Statements
//Lines of codes will need to repeat???
}
else if (/* Book a room*/) { Is it efficient???
//Statements
//Lines of codes
…………………………………...
}
Calculating the total of empty rooms
else if (/*Check Out*/) {
//Statements
//Lines of codes
………………………………….
}
Calculating the total of empty rooms
else if (/*Promotion*/) {
//Statements
//Lines of codes
………………………………….
}
Calculating the total of empty rooms
else {
//Exit
//Lines of codes
}

//Continue to the main menu? Yes or No?


}while(/*repeat the menu if yes*/)
}
Introduction
Problem – Hotel System
int main(){ //Function definition
do { void Registration(/*passing of variables*/){
if (/*Registration*/) //Statements
//Function of Registration }
else if (/* Book a room*/) {
//Function of Booking void Booking(/*passing of variables*/){
ONLY 1 //Function of CalculatingEmptyRooms //Statements
LINE TO } }
CALL THE else if (/*Check Out*/){
FUNCTIO void CheckOut(/*passing of variables*/){
//Function of Check Out
N //Statements
//Function of CalculatingEmptyRooms
} }
else if (/*Promotion*/){
//Function of CalculatingEmptyRooms void Exit(/*passing of variables*/){
} //Statements
else }
//Function of Exit
void CalculatingEmptyRooms(/*passing of variables*/){
//Continue to the main menu? Yes or No? //Statements
}while(/*repeat the menu if yes*/) }
}
Introduction
The advantages of function are:
■ Abstraction: While working on one function, you can focus on just that part
of the program and construct it, debug it, and perfect it.
■ Encapsulation: Different people can work on different functions
simultaneously
■ Reusability: If a function is needed in more than one place in a program or
in different programs, you can write it once and use it many times.
■ Maintainability: Using functions greatly enhances the program’s readability
because it reduces the complexity of the function main.

** OOP will show you better ways to achieve all the properties mentioned above.
Pre-Defined functions
Pre-Defined functions
Example of Pre-Defined function
int main()
{
int A = 2, B = 2, C;

pre-defined function
C = pow(A, B);
#include <cmath>
cout << C << endl;

system("pause");
return 0;
}
User-defined functions

■ There are times (most of the time) that we need to create


custom functions.
■ Programmers need to define (or create) own functions in order
to run the whole program.
Example of User-Defined function
//Function prototype //user-defined function
double power(double A, int B); double power(double A, int B) {
double C = A;
int main() for (int i = 0; i < B-1; i++)
{ C = C * A;
int C;
C = power(5, 3); //Function call return C;
cout << C << endl; }

system("pause");
return 0;
}
Function
■ A function includes
name: name of the function. Function names follow same
rules as variable names
parameter list: variables that hold the values passed to the
function
body: statements that perform the function’s task
return type: data type of the value the function returns to the
part of the program that called it

6-19
Main Function

6-20
Function
RETURN NAME
TYPE PARAMETER LIST

double power(double A, int B) {


double C = A;
for (int i = 0; i < B-1; i++)
BODY
C = C * A;

return C;
}
Defining and Calling Functions
■ Function call: statement that causes a function to execute
■ Function definition: statements that make up a function

6-22
Calling a Function
■ To call a function, use the function name followed by ()
and ;
printHeading();
■ When a function is called, the program executes the body of
the function
■ After the function terminates, execution resumes in the calling
module at the point of call

6-23
Calling a Function
■ main is automatically called when the program starts
■ main can call any number of functions
■ Functions can call other functions

6-24
Function Header
■ The function header consists of
– the function return type
– the function name
– the function parameter list
■ Example:
int main()
■ Note: no ; at the end of the header

6-25
Function Prototypes
The compiler must know the following about a function before
it is called
– name
– return type
– number of parameters
– data type of each parameter

6-26
Function Prototypes
Ways to notify the compiler about a function before a call to the
function:
– Place function definition before calling function’s definition
– Use a function prototype (similar to the heading of the
function
■ Heading: void printHeading()
■ Prototype: void printHeading();

6-27
Prototype Notes

■ Place prototypes near top of program


■ Program must include either prototype or full function
definition before any call to the function, otherwise a
compiler error occurs
■ When using prototypes, function definitions can be placed in
any order in the source file. Traditionally, main is placed
first.

6-28
Parameters, Prototypes, and Function Headings
(3 important things)
■ For each function argument,
– the prototype must include the data type of each parameter in its
()
void displayValue(int); //prototype
– the heading must include a declaration, with variable type and
name, for each parameter in its ()
void displayValue (int num) //heading
■ The function call for the above function would look like this:
displayValue(5); //call
6-29
Example of User-Defined function
#include <iostream>
using namespace std; FUNCTION
//user-defined function
FUNCTIO
PROTOTYP N
double power(double A, int B); E HEADER
double power(double A, int B) {
int main() double C = A;
{ for (int i = 0; i < B-1; i++)
int C; FUNCTIO
N
C = C * A; FUNCTION
DEFINITION
CALL
C = power(5, 3);
cout << C << endl; return C;
}
system("pause");
return 0;
}
Example of User-Defined function

Function Prototype

Function Call Same


Title

Function Header
Function Definition
(Body)
User-defined functions
Value-Returning Functions
Function Return Type
■ If a function returns a value, the type of the value must be
indicated
int main()
■ If a function does not return a value, its return type is void
void printHeading()
{
cout << "\tMonthly Sales\n";
}

6-34
Returning a Value – the return Statement
■ Format: return expression;
■ expression may be a variable, a literal value, or an
mathematical expression.
■ expression should be of the same data type as the
declared return type of the function (will be converted if not)

6-35
Value-Returning Functions
2
1
1. Title of function header, function call and function
prototype must be the same.
2
1 2. The data type and the number of parameters and
arguments of function header, function call and
function prototype must be the same.

2
1
Value-Returning Functions
3. The value of ‘x’ is passed to ‘a’ when the function call
happens; hence value of ‘a’ is equal to ‘x’.
It is similar when value of ‘y’ is passed to ‘b’.

4. The variables in the function are local variables; their


values can only be determined within the function. User
5 needs to determine the return values to pass back to
main function.
3
5. If there is only one return value, user can determine the
type of the function. E.g. only ‘max’ is return to the
5 main function; hence, the type of the function can be
4 double.

6. The ‘max’ that computed in the function will be assigned


to the ‘value’ in the main function.

5
6
Example of value-returning function
Calling the function
Function creation structure

Function Declaration/
Function Prototype

Function Call

Function Call
Function creation structure
Function Call

Function Definition

Function Definition
Nested function call
Calling function
Returning a Boolean Value
■ Function can return true or false
■ Declare return type in function prototype and heading as bool
■ Function body must contain return statement(s) that return
true or false
■ Calling function can use return value in a relational expression

6-44
Boolean return Example
bool isValid(int); // prototype
bool isValid(int val) // heading
{
int min = 0, max = 100;
if (val >= min && val <= max)
return true;
else
return false;
}
if (isValid(score)) // call

6-45
Example of function
Function Void Type
■ Function that never return anything.
Example of void function

Output 
Void Functions 1. Title of function header, function call
and function prototype must be the
same.

2 2. The data type and the number of


parameters and arguments of function
1 header, function call and prototype
definition must be the same.

3. The value of ‘x’ is passed to ‘a’ when


the function call happens; hence value of
‘a’ is equal to ‘x’. It is similar when
1 2 value of ‘y’ is passed to ‘b’.
3 4. The variables in the function are local
2 variables; their values can only be
1 determined within the function.

5. No variable is returned to the main


function since it is declared as void type.
// This program demonstrates a function with a parameter.
#include <iostream>
using namespace std;

// Function prototype
void displayValue(int num);

int main()
{
cout << "I am passing 5 to display Value.\n";
displayValue(5); // Call displayValue with argument 5
cout << "Now I am back in main.\n";
return 0;
}

/********************************************
* displayValue *
* This function uses an integer parameter *
* whose value is displayed. *
********************************************/
void displayValue(int num)
{
cout << "The value is " << num << endl;
} 6-50
// This program demonstrates a function with three parameters.
#include <iostream>
using namespace std;

// Function prototype
void showSum(int num1, int num2, int num3); //end with ;

int main()
{
int value1, value2, value3;

// Get 3 integers
cout << "Enter three integers and I will display ";
cout << "their sum: ";
cin >> value1 >> value2 >> value3;

// Call showSum, passing 3 arguments.


showSum(value1, value2, value3); //must send 3 arguments to the function
return 0;
}

/********************************************
* showSum *
* This function displays the sum of the *
* 3 integers passed into its parameters. *
********************************************/
void showSum(int num1, int num2, int num3) // n o ;
{
cout << "The sum is " << (num1 + num2 + num3) << endl;
}
6-51

You might also like