Chap09 - User-Defined Functions
Chap09 - User-Defined Functions
Chap09 - User-Defined Functions
Programming
datatype function_name(){
Chapter 9
}
• 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
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
void header() { //
Definition
cout << “Function”;
}
8
Function Declaration / Prototype
• General format for a prototype: Parameter
return-type function_name (arg_type arg);
• 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
◼ 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 = “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;
}
Local variable
• Declared within the function body
• Not accessible by other functions
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
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;
}
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
36
Functions – Pass by Value
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
duplicating
⦿ 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;
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
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
57