Chap09 - User-Defined Functions
Chap09 - User-Defined Functions
2
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)
calling module
Generate_bill
called modules /
Read_user_data Print_bill
calling module
7 called modules
Writing a Function
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);
• 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
◼ 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:
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 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
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
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);
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;
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
}
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
48
Menus – Rules of Thumb
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;
52
Multi Level Menu
Option 1 Option 2
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
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.
57