Chap09 - User-Defined Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

C++ Programming:

Problem Solving and


how create function

Programming
datatype function_name(){
Chapter 9
}

int main(){ User-Defined Functions


}
Why Function?

• Modular programming enables us to


organize a program into small, independent
modules/functions that are separately named
& individually invoke-able program elements.
• Each module performs separate task with a
single purpose.
double/string BIG TASK
datatype will be returnable or non returnable

TASK A the task have single


task
don't need add another function

TASK B TASK C TASK D


2
Why Function?

• Structured programming enables the large


problem to be divided (factored) into main
module and its related sub-modules.
ATM is main function The
division of modules proceeds until the module
consists of only the elementary process,
which cannot be further divided.
Example:
You wish to build a program that simulates
ATM, what are the main modules?
3
(Hint: Think of the menu on the ATM)
Why Function?
Manageable • Problems can be factored into readable, understandable
and manageable steps
code
Reusable • Enables the same code to be reused (e.g. the same line
can be printed several times to separate multiple
code sections)

only give main function


To protect • Make the related data available only if they are needed
(e.g. withdrawal amount is not related to deposit
data amount, then they should not be lumped together)

• Easy to find errors since can focus into and work on the
Easy to debug module easily which contains the error

4
Why Function?

⦿ Rules of thumb:
1) Contributes to only ONE main task
2) Consists of single entry and single exit
3) Use meaningful name for the module
e.g. calculateSalesTax
4) May or may not return a value (result)
declare in returnable or non returnable

⦿ Can use structure chart to show the


hierarchical relationship among all the
5
modules.
Why Function? - Example
Enter phone number: 010-12387654
Enter call usage: 29.50
-------------------------------------------
Phone bill summary
-------------------------------------------
phone number: 010-12387654
User name: Jessie W. Smith
call usage from 1-10-2013 to 31-10-2013
call: RM 29.50
billing: RM 5.00
Total: RM 34.50
Please pay bill by 10-11-2013. Thank you.

Suggest how would you modularize the program above.


Why Function? - Example
main function
objective of this problem

Generate_bill calling module

Print_bill
called modules /
Read_user_data
calling module
pass

Search_user_ Calculate_phone_
Print_header Print_deadline
name bill

7 called modules
Writing a Function

Declaration void header(); function prototype

void main() {// s


Call header();//. called module
} end main

void header() { //
Definition
cout << “Function”;
}
8
Function Declaration / Prototype
• General format for a prototype: Parameter
return-type function_name (arg_type arg);

− return-type : What value the function will return


− function_name : What function will be called
− arg_type arg : What arguments to be passed

• Example:
double Calculate(int x, int y); OR
double Calculate(int , int );
return-type function_name arg_type arg

9
Function Definition
• Contains the code to complete a task
• Made up of function header and function
body
• Rules of thumb:
1. Function header: May (or may Data_type
not) receive some data through Name(argument_list)
its argument list / parameters {
2. Function Body: Used to perform
specific actions for the function. //process the
3. Return Statement: May (or may function_value
not) return the function value return function_value;
to the calling module/function.
}
10
Function Definition
⦿ TWO types of function:
◼ Void Functions non returnable function
• Does NOT return a function value.
• Can receive value from the calling
function

◼ Value-returning Functions returnable function


• Will return the function value to the
calling module/function.
• Use return statement.
11
res 8

void function already accept and


pass the answer

void Print_result(int); void Print_result(int ans)


int main() { return nothing
{ function prototype cout << “The answer is “
int res =5 + 3; << ans;
Print_result(res); }
return 0;
no return statement
} function call

in the calling in the called


module/function module/function
12 What is the output?
Value returning function
accept two arguments(integer)

int sum_num(int, int); int sum_num(int x1, int x2)


int main() {
{ function prototype int answer= x1 + x2;
int res = sum_num(2,3); return answer;
cout << res; } arguments /
parameters
return 0;
} function call return a function value

in the calling in the called


module/function module/function

13 What is the output?


Function call
◼ Call a function by using the function name with ( ).
◼ List parameters inside the bracket ( ) if it is defined.

◼ Examples:

Addition(x, y);
// passing x and y into function to do addition
Display_Menu();
// just to perform display in the function
char grade; …..
grade = FindGrade(mark);
// passing mark into function and store the
14 returned grade value
Function call
◼ Examples:

cout << calculate(x) ;


// print the value returned by the function directly
rather than assign to a variable
if (password(name, passw)) OR
switch (checkGrade(mark)) { … } OR
while (calculate(x) < 100) { … }
// use in if, switch and any loop statements to check
the value returned by the function

15
Program using function

function prototype /
function declaration

argument
calling function
Program using function
Function - Question
⦿ Fill in the blank
__①____ __②__ multiply(_③_ num)
int main() {
{ _④_ ans =2 * num;
double res =
multiply(3.2); return ans;
cout << res; }
return 0;
}

output 6.4
18
Function - Question
⦿ Fill in the blank
__①____ __ ③ _ get_response(_ ④ _ F)
int main() {
{ bool flag = true; string response = “ ”;
string resp = “ ”; if (F==true)
/*get resp from response = “Bingo”;
get_response else
based on flag */ response = “Next”;
__②__ return response;
cout << resp; }
return 0;
} output Bingo
Function - Question
⦿ Fill in the blank
__①____ _ ③ _ print_res(_④_Result)
int main() {
{ cout << Result;
string res = “Hello World”; }
/*call print_res */
__②__
return 0;
}

output Hello World


Function - Question
⦿ Redesignthe code below by using
modularization and produce the structure chart.
int main(){
int x1, x2, x3, total;
do{
cout << “Enter 3 positive numbers: ”;
cin >> x1 >> x2 >> x3;
} while(x1 < 0 || x2 < 0 || x3 < 0);
total = x1 + x2 + x3;
cout << “The total is “ << total;
return 0;
}
Variable Scope

Local variable
• Declared within the function body
• Not accessible by other functions

Global variable can share to any

• Declared outside of any functions in a program


• Accessible to all functions within the program
22
Local Variables

int sum_num(int, int); int sum_num(int x1, int x2)


int main() {
5 2 3
{ local variable int answer= x1 + x2;
int res = sum_num(2,3); return answer;
cout << res; CF
}
return 0; x1, x2 and answer are
} local variables
res is a local variable

in the calling in the called


23 module/function module/function
Local Variables - Examples
int main()
{ inside main
int a=20, x=20, n=0; Output:
n = calculate(x); 200
cout << a << endl;
return 0; 20
}
int calculate(int x)
{ inside function
int a; //different from variable a in main( )
a = x * 10;
cout << a << endl;
return a;
24 }
Local Variables - Examples

int main()
Output:
{
First: 20
int x = 20;
Second: 30
cout << "First: " << x << endl;
Third: 20
{
int x = 30;
cout << "Second: " << x << endl;
}
cout << "Third: " << x << endl;
return 0;
}

25
Global Variables
global variable

int sum_num(int, int); int sum_num()


int x1 = 2, x2 = 3; { x1 and x2 are global variables
int main() int answer= x1 + x2;
x1 and x2 are global
{ return answer;
variables
local variable
int res = sum_num(); }
cout << res; answer is a local variable
return 0;
}
res is a local variable

in the calling in the called


26
module/function module/function
Global Variables - Examples
int calculate(int x);
int a; //global scope
int main() {
int x=20, n=0; Output:
a = 20;
n = calculate(x); 200
cout << a << endl; 200
return 0;
}
int calculate(int x) {
a = x * 10; // doesn’t need to declare a as local var.
cout << a << endl;
return a;
27
}
Scope Rules
1. A function name has global scope. Function
definitions cannot be nested within function
definitions.
int main() int main()
{ cout << sum_num(); {
return 0; int sum_num()
} {
int sum_num() return something;
{ }
return something; return 0;
} }

28
OK WRONG!
Scope Rules
2. The scope of a function parameter = local
variable declared in the function body
int sum_num(int x1, int x2)
{
int ans = x1 + x2;
return ans;
}

x1, x2 and ans are within the same scope

29
Scope Rules
3. The scope of global variable (or constant)
extends from its declaration to the end of the
program (except Rule 5)
int main()
{ cout << globalX; // Error!!!
return 0;
}
int globalX = 100; //declaration
int sum_num() for sum_num not main

{ int ans = globalX * 2;


return ans;
30
} //end of program
Scope Rules
4. The scope of a local variable (or constant)
extends from its declaration to the end of the
block in which it is declared, includes any
nested blocks (except Rule 5)
void Reduce_num()
{ int count= 10; //declaration
while(count > 0)
{ int n = 1; scope for n
n = n * count;
count--;
scope for count
}
31 }
Scope Rules
5.The scope of an identifier does not include
any nested block that contains a locally
declared identifier with the same name (local
identifiers have name precedence).
int X = 100; //declaration
int main()
{ cout << X; this use global X
cout << sum_num();
return 0;
}
int sum_num() different x
{ int X = 2; this use local X
return X * 3 }
32
Scope Rules – Question
⦿ Chee Meng wrote his main function as
shown below. What mistake has he done?
int sum_num();
int main()
{ int X;
cin >> X;
void print_num()
{ int ans = X * 3;
cout << ans; }
return 0;
}
33
Scope Rules - Question
⦿ Given the code below, what are the mistakes?
1 int calculate_tax();
2 const double rate = 3.1;
3 void main()
4 { double amount, total;
5 cin >> amount; //assuming amount = 10;
6 calculate_tax(amount);
7 cout << total;
8 }
9 double calculate_tax()
10 { total = amount * rate;
11 return total;
34 12 }
Scope Rules - Question
⦿ Given the code below, what is the output?
int multiply(int); void print_x();
int x = 10;
int multiply(int a)
void main()
{ int x = 5;
{ int y, ans;
return x * a;
cin >> y; //assume y = 5;
}
ans = multiply(y);
void print_x()
cout << x <<endl <<
{ x = 100;
“answer=“<< ans << endl;
cout << “x = ” << x;
print_x();
cout << endl;
cout << “x = ” << multiply(1);
}
}
Functions with parameters

⦿ 3 types of functions with parameters:


 Pass by Value
 Pass by Reference referring to other variables
A-refers to B
B-will tell you A have this
 Pass by Address
pointer

referring other address

36
Functions – Pass by Value

⦿ A copy of the data is created and placed


in a local variable in the called function.
⦿ Regardless of how the data are
manipulated and changed in the called
function, the original data in the calling
function are safe and remain unchanged.
⦿ This is the preferred passing technique
because it protects the data.

37
Functions – Pass by Value
#include <iostream>
using namespace std;
void fun ( int x);

int main (void) a 5


{
prints 5 (not
int a=5;
affected by the
fun (a); function fun)
cout << a;

return 0;
}
x 5 ←only a copy
void fun (int x) {
x = x + 3;
}
Functions – Pass by Reference
duplicating

⦿ Links the variable identifiers in the calling


function to their corresponding parameters
in the called function.
⦿ Any reference to a parameter is therefore
the same as a reference to the variable in
the calling function.
⦿ When the called function changes a value,
the variable in the calling function also
changed
⦿ we need to use a reference variable (&) as
39
the parameter in the function.
Functions – Pass by Reference
# include <iostream>
using namespace std;
void fun ( int &x);
int main (void){ a
int a=5;

fun (a); ← no address operator ‘&’


cout << a; ← prints 8
return 0;
}

void fun (int &x) x


{ reference
x = x + 3; ← Does not variable
} requires ‘*’
Functions – Pass by Address

⦿ Use pointers
⦿ & (address operator): used to pass an address
pointer/dereference/
⦿ * (indirection operator): used to store data at /
to get data from an address

41
Functions – Pass by Address
# include <iostream>
using namespace std;
void fun ( int *x); a
int main() {
int a=5;

fun (&a); ← & : address operator


cout << a; ← prints 8 Dereference
return 0;
}

void fun (int *x) x ←address


{ (pointer)
*x = *x + 3; ← Requires ‘*’
to dereference
}
Exchanging Two Variables using
Pass by Reference functions
void exchange (int &num1,int &num2);
int main (void) { ↑ a b
int a, b; type includes an
…… ampersand
exchange (a, b);
…… ↑
return 0; No address operators
}

void exchange (int &num1, int &num2)


{ num1 num2
int temp; (num1 and num2 are
temp = num1; ← no ‘*’ is required reference variables)
num1 = num2;
num2 = temp; temp
}
Exchanging Two Variables using
Pass by Address functions
void exchange ( int *num1, int *num2);
int main (void) ↑ a b
{ type includes an asterisk
int a, b;
……
exchange (&a, &b);
…… ↑ Dereferences
return 0; address
} operators

void exchange (int *num1, int *num2) {


int temp; num1 num2
temp = *num1; ← Indirection (num1 and num2 are
*num1 = *num2; operator ‘*’ is used addresses)
*num2 = temp; for dereferencing. temp
}
Functions Overloading
⦿ Overloading a function
◼ Several functions with the same name, but
different parameter lists

⦿ Parameter types determine which function


will execute. Must provide the definition of
each function.

⦿ Can overload two or more functions by:


◼ Having a different number of parameters
◼ Having the same number of parameters, but
45
• Parameter types should be in different order
• At least one parameter type should be different
Functions Overloading - Example
// overloaded function int main ()
#include <iostream> {
using namespace std; int x=5,y=2;
float n=5.0,m=2.0;
int divide (int a, int b) { 2
return (a/b); cout << divide (x,y);
} cout << "\n";
2.5

float divide (float a, float b) cout << divide (n,m);


{ cout << "\n";
return (a/b);
}46
return 0;
}
//Function overloading int main()
#include <iostream> { char ch1, ch2;
using namespace std; cout << "Enter two characters : ";
void swap (char &x, char &y) cin >> ch1 >> ch2;
{ char t; swap (ch1, ch2);
t=x; cout << "After swapping : " << ch1
x=y; << " " << ch2 << endl;
y=t; } int a, b;
cout << "\nEnter two integer numbers : ";
void swap (int &x, int &y) cin >> a >> b;
{ int t; swap (a, b);
t=x; cout << "After swapping : " << a
x=y; << " " << b << endl;
y=t; } float x, y;
cout << "\nEnter two floating point numbers
void swap (float &x, float &y) : ";
{ float t; cin >> x >> y;
t=x; swap (x, y);
x=y; cout << "After swapping : " << x << " "
y=t; } << y << endl;
return 0; }
Applications of Functions/Modules

Menus
⦿Interactive program that displays a set of
options to the user.
⦿Single-level menu: Selection from only one
menu.
⦿Multi-level menu: selection of one option
leads to another menu with further, refined
selections.

48
Menus – Rules of Thumb

1. Menus should always have a “quit” choice.


2. It is important to keep track of bad user input

49
Single Level Menu
⦿ Given the main program as follows, write
the C++ function called “displayMenu” to
display the menu of previous slide.
void displayMenu() {
cout << “Select Challenge\n”;
cout << “----------------\n”;
cout << “1. Addition\n”;
cout << “2. Subtraction\n”;
cout << “3. Multiplication\n”;
cout << “4. Division\n”;
cout << “5. Quit Program\n”;
}

50
Single Level Menu
void Addition(); switch(choice) {
void Subtraction(); case 1: Addition();
void Multiplication(); break;
void Division(); case 2: Subtraction();
void main() { break;
int choice; :
do{ default: cout<< “Input
cout << "\tWELCOME\n" invalid!”;
<< "\t-------\n\n“; } while (choice!= 5);
displayMenu(); }
cout << “Enter your
choice:  ”;
cin >> choice;

Remark: Use do while loop and switch statement for


handling menu processing
Multi Level Menu

⦿ This is good to be used when


• there are too many options
• users would get confused by too many
choices
• screen is too crowded and not organized
• crowded screen reduce readability and error
prone

52
Multi Level Menu

Option 1 Option 2

53 Which one better?


Multi Level Menu - Exercise

⦿ Write the C++ program for the menu


functions at previous slide.

54
Input Validation
⦿ Incorrect user entries are the most
common errors.
⦿ Failing to account for valid responses will
lead to runtime errors.
⦿ Questions to ask:
◼ Is the user input within the given range?
◼ Does the user input follow desired format?
◼ Is the user input reasonable?

55
Input Validation - Exercise

⦿ Consider the program below. Suggest the


potential bad user data for each field.

Fill in the form


---------------------
Name:
Age:
Email:

Indicate your satisfaction of Product A:


<1-Satisfied; 2-Somewhat satisfied; 3-Not satisfied> : 

56
Input Validation - Exercise

⦿ Consider you would like to validate the AGE


entered by the user, which must fulfill the
following criteria:
1. It must be a number
2. It must be 18 or above, and below 80.

You should display appropriate error message.

Write a Pseudocode to represent your solution

57

You might also like