0% found this document useful (0 votes)
10 views57 pages

Chap09 - User-Defined Functions

Uploaded by

black hello
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views57 pages

Chap09 - User-Defined Functions

Uploaded by

black hello
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 57

C++ Programming:

Problem Solving and


Programming
Chapter 9
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.

2
Why Function?

• Structured programming enables the large


problem to be divided (factored) into main
module and its related sub-modules. 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?

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)

⦿ 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

calling module
Generate_bill

called modules /
Read_user_data Print_bill
calling module

Search_user_ Calculate_phon Print_deadlin


Print_header
name e_ bill e

7 called modules
Writing a Function

Declaration void header();

void main() {
Call header();
}

void header() {
Definition
cout << “Function”;
}
8
Function Declaration / Prototype
• General format for a prototype:
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 );

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 Data_type
may not) receive some Name(argument_list)
data through its argument {
list / parameters
2. Function Body: Used to
//process the
perform specific actions function_value
for the function. return function_value;
3. Return Statement: May (or }
10 may not) return the
function value to the
Function Definition
⦿ TWO types of function:
◼ Void Functions

Does NOT return a function value.

Can receive value from the calling
function
◼ Value-returning Functions

Will return the function value to the
calling module/function.

Use return statement.
11
void function
void Print_result(int); void Print_result(int ans)
int main() { return nothing
{ function prototype cout << “The answer is
int res =5 + 3; “
Print_result(res); << ans;
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
int sum_num(int, int); int sum_num(int x1, int
int main() x2)
{ function prototype {
int res = int answer= x1 + x2;
sum_num(2,3); arguments /
return answer;
parameters
cout << res; }
return 0; return a function value
function call
}

in the calling module/function in the called 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 =
get_response “Bingo”;
based on flag */ else
__②__ response =
cout << resp; “Next”;
return 0; return response;
} }
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
⦿ Redesign the 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
• 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


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

in the calling module/function in the called module/function


23
Local Variables - Examples
int main()
{
int a=20, x=20, n=0; Output:
n = calculate(x); 200
cout << a << endl;
return 0; 20
}
int calculate(int x)
{
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:
cout << "First: " << x << endl;
30
{
Third: 20
int x = 30;
cout << "Second: " << x << endl;
}
cout << "Third: " << x << endl;
return 0;
}

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

cout << res;


return 0; variable
res is a local
}
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;
200
n = calculate(x);
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(); int sum_num()
return 0; {
} return
int sum_num() 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()
{ 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() this use global X
{ cout << X;
cout << sum_num();
return 0;
}
int sum_num()
this use local X
32 { int X = 2;
return X * 3 }
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
6 = 10;
7 calculate_tax(amount);
8 cout << total;
9 }
10 double calculate_tax()
11 { total = amount * rate;
34 12 return total;
}
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 = ” <<
print_x(); x;
cout << “x = ” << cout << endl;
multiply(1); }
}
Functions with parameters

⦿ 3 types of functions with parameters:


 Pass by Value
 Pass by Reference
 Pass by 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 affected
int a=5; by the
function fun)
fun (a);
cout << a;

return 0;
}
x 5 ←only a copy
void fun (int x) {
x = x + 3;
}
Functions – Pass by Reference
⦿ 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);
a
int main (void){
int a=5;

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


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

x
void fun (int &x)
{ reference
x = x + 3;← Does not
} requires ‘*’ variable
Functions – Pass by Address

⦿ Use pointers
⦿ & (address operator): used to pass an address
⦿ * (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;
← & : address operator
fun (&a);
cout << a;← prints 8
return 0; Dereference
}

void fun (int *x)


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

……
No address operators
return 0;
}
void exchange (int &num1, int
&num2) num1
{ num2
int temp; ← no ‘*’ is required
(num1 and num2 are
temp = num1; reference variables)
num1 = num2;
num2 = temp;
temp
}
Exchanging Two Variables using
Pass by Address functions
void exchange ( int *num1, int
*num2); ↑ a b
int main (void)
type includes an asterisk
{
int a, b;
……
exchange (&a,↑ &b); Dereferences
…… address operators
return 0;
}
void exchange (int *num1, int *num2)
{ num1
int temp; ← Indirection num2
temp = *num1; operator ‘*’ is (num1 and num2 are
*num1 = *num2; used for
addresses)
*num2 = temp;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
• Parameter types should be in different order
45
• 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
void swap (float &x, float &y) numbers : ";
{ 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