0% found this document useful (0 votes)
29 views

07 Function - Part2

This document provides an overview of functions in C++ including: 1. Calling functions with multiple arguments by passing each argument to its corresponding parameter. 2. Reference parameters that allow a function to modify the original argument passed to it. 3. Global variables that can be accessed by any function and retain their value between function calls.

Uploaded by

ZHEN-HONG LEE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

07 Function - Part2

This document provides an overview of functions in C++ including: 1. Calling functions with multiple arguments by passing each argument to its corresponding parameter. 2. Reference parameters that allow a function to modify the original argument passed to it. 3. Global variables that can be accessed by any function and retain their value between function calls.

Uploaded by

ZHEN-HONG LEE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

FUNCTIONS

PART 2
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
Calling Functions with Multiple Arguments

When calling a function with multiple arguments


– the number of arguments in the call must match the
function prototype and definition
– the first argument will be copied into the first
parameter, the second argument into the second
parameter, etc.

6-3
Calling Functions with Multiple Arguments
Illustration
displayData(height, weight); // call

void displayData(int h, int w)// heading


{
cout << "Height = " << h << endl;
cout << "Weight = " << w << endl;
}

6-4
Parameter Types
■ In general, there are two types of formal parameters: value
parameters and reference parameters.
Parameter Types
Reference Variables
■ A reference variable is an alias for another variable
■ Defined with an ampersand (&)
void getDimensions(int&, int&);
■ Changes to a reference variable are made to the variable it
refers to
■ Use reference variables to implement passing parameters by
reference
■ Function can be defined without return type.

6-7
Reference Variable Notes
■ Each reference parameter must contain &
■ Argument passed to reference parameter must be a variable
(cannot be an expression or constant)
■ Use only when appropriate, such as when the function must
input or change the value of the argument passed to it
■ Files (i.e., file stream objects) should be passed by reference

6-8
Reference Variable

1. 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’.

2. The variables in the function are local variables;


their values can only be determined within the
function.

3. ‘add’ is the reference variable; the ‘add’ in the main


function is attached to the ‘add’ in the addition
function.

4. Either ‘add’ value change in main or addition


function, both value will change together.
// This program uses a reference variable as a function parameter.
#include <iostream>
using namespace std; The & here in the prototype indicates that the parameter is a reference variable.

// Function prototype. The parameter is a reference variable.


void doubleNum(int &refVar);

int main()
{ Here we are passing value by reference.
int value = 4;

cout << "In main, value is " << value << endl;
cout << "Now calling doubleNum..." << endl;
doubleNum(value);
cout << "Now back in main, value is " << value << endl;
return 0;
}

/**************************************************************
* doubleNum *
* This function's parameter is a reference variable. The & *
* tells us that. This means it receives a reference to the *
* original variable passed to it, rather than a copy of that *
* variable's data. The statement refVar *= 2 is doubling the *
* data stored in the value variable defined in main. *
**************************************************************/
void doubleNum (int &refVar)
{
refVar *= 2;
The & also appears here in the function header.
}
6-10
Pass by Reference Example

void squareIt(int &); //prototype


void squareIt(int &num)
{
num *= num;
}
int localVar = 5;
squareIt(localVar); // localVar now
// contains 25

6-11
Why we need reference parameter?

■ What if we need to return 2 or more values? E.g. swap


function.

■ Can you write a function to swap the values between 2


variables?
Scope of an Identifier
Local Variable Lifetime

■ A local variable only exists while its defining function is


executing
■ Local variables are destroyed when the function terminates
■ Data cannot be retained in local variables between calls to
the function in which they are defined

6-14
Passing Data by Value
■ Pass by value: when argument is passed to a function, a copy of
its value is placed in the parameter
■ Function cannot access the original argument
■ Changes to the parameter in the function do not affect the value
of the argument in the calling function (if it is not a referenced
type)

6-15
Passing Data to Parameters by Value
■ Example: int val = 5;
evenOrOdd(val);

val num
5 5
argument in parameter in

calling function evenOrOdd function

■ evenOrOdd can change variable num, but it will have no


effect on variable val

6-16
// This program demonstrates that changes to a function
// parameter have no effect on the original argument.
#include <iostream>
using namespace std;

// Function Prototype
void changeMe(int aValue);

int main()
{
int number = 12;

// Display the value in number


cout << "In main number is " << number << endl;

// Call changeMe, passing the value in number as an argument


changeMe(number);

// Display the value in number again


cout << "Back in main again, number is still " << number << endl;
return 0;
}

void changeMe(int myValue)


{
// Change the value of myValue to 0
myValue = 0;

// Display the value in myValue


cout << "In changeMe, the value has been changed to “
<< myValue << endl;
6-17
}
// This program shows that variables defined in a function
// are hidden from other functions.
#include <iostream>
using namespace std;

void anotherFunction(); // Function prototype

int main()
{
int num = 1; // Local variable

cout << "In main, num is " << num << endl;
anotherFunction();
cout << "Back in main, num is still " << num << endl;
return 0;
}

/***************************************************************
* anotherFunction *
* This function displays the value of its local variable num. *
***************************************************************/
void anotherFunction()
{
int num = 20; // Local variable
cout << "In anotherFunction, num is " << num << endl;
}
6-18
When the program is executing in main, the num variable defined in main is

visible. When anotherFunction is called, however, only variables

defined inside it are visible, so the num variable in main is hidden.

6-19
Function using Global Variable
■ In function, instead of using return or reference variable,
global variable can also be used in order to change the value.
■ Function can be defined without return anything.
■ The variables are declared globally.
■ The global variable can be accessed by any function including
main function.
■ The global variable that change in any function will amend the
value globally.
Global Variable
1. 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’.

2. The variables in the function are local


variables; their values can only be determined
within the function.

3. ‘add’ is a global variable which declare outside


of any function.

4. Hence, ‘add’ can be accessed by any function.

5. Either ‘add’ value change in any function, it will


change globally.
// This program shows that a global variable is visible to all functions
// that appear in a program after the variable's definition.
#include <iostream>
using namespace std;

void anotherFunction(); // Function prototype


int num = 2; // Global variable

int main()
{
cout << "In main, num is " << num << endl;
anotherFunction();
cout << "Back in main, num is " << num << endl;
return 0;
}

/***************************************************************
* anotherFunction *
* This function changes the value of the global variable num. *
***************************************************************/
void anotherFunction()
{
cout << "In anotherFunction, num is " << num << endl;
num = 50;
cout << "But, it is now changed to " << num << endl;
}
6-22
Function with Default Parameters
Function with Default Parameters
Using Functions in a Menu-Driven Program

Functions can be used


■ to implement user choices from menu
■ to implement general-purpose tasks
- Higher-level functions can call general-
purpose functions
- This minimizes the total number of functions
and speeds program development time

6-25
// Function prototypes
void displayMenu();
int getChoice();
void showFees(string category, double rate, int months);

int main()
{
// Constants for monthly membership rates
const double ADULT_RATE = 40.00,
SENIOR_RATE = 30.00,
CHILD_RATE = 20.00;
int choice, // Holds the user's menu choice
months; // Number of months being paid

// Set numeric output formatting


cout << fixed << showpoint << setprecision(2);

do
{ displayMenu();
choice = getChoice(); // Assign choice the value returned
// by the getChoice function
if (choice != 4) // If user does not want to quit, proceed
{
cout << "For how many months? ";
cin >> months;
switch (choice)
{
case 1: showFees("Adult", ADULT_RATE, months);
break;
case 2: showFees("Child", CHILD_RATE, months);
break;
case 3: showFees("Senior", SENIOR_RATE, months);
}
}
} while (choice != 4);
return 0;
} 6-26
void displayMenu()
{
system("cls"); // Clear the screen.
cout << "\n Health Club Membership Menu\n\n";
cout << "1. Standard Adult Membership\n";
cout << "2. Child Membership\n";
cout << "3. Senior Citizen Membership\n";
cout << "4. Quit the Program\n\n";
}

int getChoice()
{
int choice;

cin >> choice;


while (choice < 1 || choice > 4)
{ cout << "The only valid choices are 1-4. Please re-enter. ";
cin >> choice;
}
return choice;
}

void showFees(string memberType, double rate, int months)


{
cout << endl
<< "Membership Type : " << memberType << " “
<< "Number of months: " << months << endl
<< "Total charges : $" << (rate * months) << endl;

// Hold the screen until the user presses the ENTER key.
cout << "\nPress the Enter key to return to the menu. ";
cin.get(); // Clear the previous \n out of the input buffer
cin.get(); // Wait for the user to press ENTER
}
6-27
Function Overloading
Overloaded Functions Example

If a program has these overloaded functions,


void getDimensions(int); // 1
void getDimensions(int, int); // 2
void getDimensions(int, double); // 3
void getDimensions(double, double);// 4
then the compiler will use them as follows:
int length, width;
double base, height;
getDimensions(length); // 1
getDimensions(length, width); // 2
getDimensions(length, height); // 3
getDimensions(height, base); // 4

6-29
Function Overloading
// This program uses overloaded functions.
#include <iostream>
#include <iomanip>
using namespace std;

// Function prototypes
int square(int);
double square(double);

int main()
{
int userInt;
double userReal;

//Get an int and a double


cout << "Enter an integer and a floating-point value: ";
cin >> userInt >> userReal;

// Display their squares


cout << "Here are their squares: ";
cout << fixed << showpoint << setprecision(2);
cout << square(userInt) << " and " << square(userReal) << endl;
return 0;
}

int square(int number)


{
return number * number;
}

double square(double number)


{
return number * number;
}
6-31
Warning

■ C++ does not allow the nesting of functions. That is, you
cannot include the definition of one function in the body of
another function.
Common Error 1
Common Error 1

■ Answer
Common Error 2
Common Error 3

■ Function is not GOTO !

■ Every time a function is called, an instance of the function is


created.

■ Make sure you let them finish their tasks in peace.


Common Error 4
■ If a function is not GOTO, recursion is not loop.
■ Example of Recursive Function
Void Recurse(){
… .. …
Recurse();
… .. …
}

Int main(){
… .. …
Recurse();
… .. …
}
Example of Recursion
#include <iostream>
using namespace std;
Output:
void numberFunction(int i) { The number is: 0
    cout << "The number is: " << i << endl; The number is: 1
    i++;
The number is: 2
The number is: 3
    if(i<10) { The number is: 4
        numberFunction(i); The number is: 5
The number is: 6
  }
The number is: 7
} The number is: 8
int main() {
The number is: 9

    int i = 0;
    numberFunction(i);

    return 0;
}

You might also like