person 1 (apriyanti, mirna) translate to indonesia & presentation … · person 1 (apriyanti,...
TRANSCRIPT
Person 1 (Apriyanti, Mirna)
Translate to Indonesia & presentation
Starting Out with C++, 3rd Edition
1
presentation
Start Next Week Personal Number 1 & 2 & 3
Chapter 6 Functions
Starting Out with C++, 3rd Edition
2
6.1 Focus on Software Engineering: Breaking Up Your Programs
• Programs may be broken up into many manageable functions.
Starting Out with C++, 3rd Edition
3
6.2 Defining and Calling Functions
• A function call is a statement that causes a function to execute. A function definition contains the statements that make up the function.
• The line in the definition that reads
Starting Out with C++, 3rd Edition
4
• The line in the definition that reads void main(void) is called the function header.
Figure 6-1
Return Type
Name
Parameter List (This one is empty)
Body
Starting Out with C++, 3rd Edition
5
void main(void){
cout << “Hello World\n”;}
Calling a Function
• Function Headervoid displayMessage()
• Function Call
Starting Out with C++, 3rd Edition
6
• Function CalldisplayMessage();
Program 6-1#include <iostream.h>
//******************************************
// Definition of function displayMessage. *
// This function displays a greeting. *
//******************************************
void displayMessage()
{
cout << "Hello from the function displayMessage. \ n";
Starting Out with C++, 3rd Edition
7
cout << "Hello from the function displayMessage. \ n";
}
void main(void)
{
cout << "Hello from main.\n";
displayMessage();
cout << "Back in function main again.\n";
}
Program Output
Hello from main.Hello from the function displayMessage.Back in function main again.
Starting Out with C++, 3rd Edition
8
Figure 6-2
void main(void)
void displayMessage(){
cout << “Hello from the function displayMessage.\n” ;}
Starting Out with C++, 3rd Edition
9
void main(void){
cout << “Hello from main.\n”;displayMessage();cout << “Back in function main again.\n”;
}
Program 6-2//The function displayMessage is repeatedly called from a loop
#include <iostream.h>
//******************************************
// Definition of function displayMessage. *
// This function displays a greeting. *
//******************************************
void displayMessage()
{
cout << "Hello from the function displayMessage. \ n";
Starting Out with C++, 3rd Edition
10
cout << "Hello from the function displayMessage. \ n";
}
void main(void)
{
cout << "Hello from main.\n";
for (int count = 0; count < 5; count++)
displayMessage(); // Call displayMessage
cout << "Back in function main again.\n";
}
Program Output
Hello from main.Hello from the function displayMessage.Hello from the function displayMessage.Hello from the function displayMessage.
Starting Out with C++, 3rd Edition
11
Hello from the function displayMessage.Hello from the function displayMessage.Back in function main again.
Program 6-3
// This program has three functions: main, first, and second.
#include <iostream.h>
//*************************************
// Definition of function first. *
// This function displays a message. *
//*************************************
Starting Out with C++, 3rd Edition
12
void first(void)
{
cout << "I am now inside the function first.\n";
}
Program continues//*************************************
// Definition of function second. *
// This function displays a message. *
//*************************************
void second(void)
{
cout << "I am now inside the function second.\n";
}
Starting Out with C++, 3rd Edition
13
void main(void)
{
cout << "I am starting in function main.\n";
first(); // Call function first
second(); // Call function second
cout << "Back in function main again.\n";
}
Program Output
I am starting in function main.I am now inside the function first.I am now inside the function second.Back in function main again.
Starting Out with C++, 3rd Edition
14
Back in function main again.
Figure 6-3void first(void){
cout << “I am now inside function first.\n”;}
void second(void){
Starting Out with C++, 3rd Edition
15
cout << “I am now inside function second.\n”;}
void main(void){
cout << “I am starting in function main.\n”;first();second();cout << “Back in function main again.\n”
}
Person 2 (Ricet, Riyana)
Starting Out with C++, 3rd Edition
16
Program 6-4// This program has three functions: main, deep, an d deeper
#include <iostream.h>
//**************************************
// Definition of function deeper. *
// This function displays a message. *
Starting Out with C++, 3rd Edition
17
// This function displays a message. *
//**************************************
void deeper(void)
{
cout << "I am now inside the function deeper.\n";
}
Program continues//**************************************// Definition of function deep. *// This function displays a message. *//**************************************void deep(){
cout << "I am now inside the function deep.\n";deeper(); // Call function deeper
Starting Out with C++, 3rd Edition
18
deeper(); // Call function deepercout << "Now I am back in deep.\n";
}void main(void){
cout << "I am starting in function main.\n";deep(); // Call function deepcout << "Back in function main again.\n";
}
Program Output
I am starting in function main.I am now inside the function deep.I am now inside the function deeper.Now I am back in deep.
Starting Out with C++, 3rd Edition
19
Now I am back in deep.Back in function main again.
Figure 6-4void deep(void){
cout << “I am now inside function deep.\n”;deeper();cout << “Now I am back in deep.\n”;
}
void deeper(void){
Starting Out with C++, 3rd Edition
20
cout << “I am now inside function deeper.\n”;}
void main(void){
cout << “I am starting in function main.\n”;deep();cout << “Back in function main again.\n”
}
Person 3 (Krisnawati, Adelia)
Starting Out with C++, 3rd Edition
21
6.3 Function Prototypes
• A function prototype eliminates the need to place a function definition before all calls to the function.
• Here is a prototype for the
Starting Out with C++, 3rd Edition
22
• Here is a prototype for the displayMessagefunction in Program 6-1
void displayMessage(void);
Program 6-5// This program has three functions: main, first, a nd second.
#include <iostream.h>
// Function Prototypes
void first(void);
void second(void);
void main(void)
{
Starting Out with C++, 3rd Edition
23
{
cout << "I am starting in function main.\n";
first(); // Call function first
second(); // Call function second
cout << “Back in function main again.\n";
}
Program Continues on next slide
Program 6-5 Continues// Definition of function first.
// This function displays a message.
void first(void)
{
cout << “I am now inside the function first.\n”;
}
// Definition of function second
// This function displays a message.
Starting Out with C++, 3rd Edition
24
// This function displays a message.
void second(void)
{
cout << “I am now inside the function second.\n”;
}
Program 6-5 Output
I am starting in function main.I am now inside the function first.I am now inside the function second.Back in function main again.
Starting Out with C++, 3rd Edition
25
Person 4 (Yafet, RianKalensun)
Starting Out with C++, 3rd Edition
26
6.4 Sending Information Into a Function
• When a function is called, the program may send values (arguments) into the function.
• Arguments are passed into parameters.
Starting Out with C++, 3rd Edition
27
void displayValue(int num){
cout << “The value is “ << num << endl;}
Program 6-6// This program demonstrates a function with a para meter.
#include <iostream.h>
// Function Prototype
void displayValue(int)
void main(void)
{
Starting Out with C++, 3rd Edition
28
cout << "I am passing 5 to displayValue.\n";
displayValue(5); //Call displayValue with argument 5
cout << "Now I am back in main.\n";
}
Program Continues to next slide
Program 6-6//*********************************************
// Definition of function displayValue. *
// It uses an integer parameter whose value is disp layed. *
//*********************************************
void displayValue(int num)
{
cout << “The value is “ << num << endl;
}
Starting Out with C++, 3rd Edition
29
Program Output
I ampassing 5 to displayValue.
The value is 5Now I am back in main.
Starting Out with C++, 3rd Edition
30
Figure 6-5
displayValue(5);
void displayValue(int num)
Starting Out with C++, 3rd Edition
31
void displayValue(int num){
cout << “The value is “ << num << endl;}
Program 6-7// This program demonstrates a function with a para meter.#include <iostream.h>
// Function Prototypevoid displayValue(int);
void main(void)
{
cout << "I am passing several values to displayValu e. \ n";
Starting Out with C++, 3rd Edition
32
cout << "I am passing several values to displayValu e. \ n";
displayValue(5); // Call displayValue with argumen t 5
displayValue(10); // Call displayValue with argumen t 10
displayValue(2); // Call displayValue with argumen t 2
displayValue(16); // Call displayValue with argumen t 16
cout << "Now I am back in main.\n";
}
Program continues on next slide
Program 6-7 Continued//*********************************************************
// Definition of function displayValue. *
// It uses an integer parameter whose value is displayed. *
//*********************************************************
void displayValue(int num)
Starting Out with C++, 3rd Edition
33
void displayValue(int num)
{
cout << "The value is " << num << endl;
}
Program Output
I am passing several values to displayValue.The value is 5The value is 10The value is 2
Starting Out with C++, 3rd Edition
34
The value is 2The value is 16Now I am back in main.
Program 6-8// This program demonstrates a function with three parameters.
#include <iostream.h>
// Function prototype
void showSum(int, int, int);
void main(void)
Starting Out with C++, 3rd Edition
35
void main(void)
{
int value1, value2, value3;
cout << "Enter three integers and I will display ";
cout << "their sum: ";
cin >> value1 >> value2 >> value3;
showSum(value1, value2, value3); // Call showSum with// 3 arguments
}
Program continues//************************************************************
// Definition of function showSum. *
// It uses three integer parameters. Their sum is displayed. *
//************************************************************
void showSum(int num1, int num2, int num3)
{
cout << (num1 + num2 + num3) << endl;
Starting Out with C++, 3rd Edition
36
cout << (num1 + num2 + num3) << endl;
}
Program Output with Example Input
Enter three integers and I will display their sum: 4 8 7 [Enter]
19
Starting Out with C++, 3rd Edition
37
Figure 6-6showSum(value1, value2, value3);
void showSum(int num1, int num2, int num3)
Starting Out with C++, 3rd Edition
38
void showSum(int num1, int num2, int num3){
cout << num1 + num2 + num3 << endl;}
Person 5 (Juli, Deasry)
Starting Out with C++, 3rd Edition
39
6.5 Changing the value of a Parameter
• When an argument is passed into a parameter, only a copy of the argument’s value is passed. Changes to the parameter
Starting Out with C++, 3rd Edition
40
value is passed. Changes to the parameter do not affect the original argument. This is called “passed by value.”
Program 6-9// This program demonstrates that changes to a func tion parameter
// have no effect on the original argument.
#include <iostream.h>
// Function Prototype
void changeThem(int, float);
void main(void)
{
int whole = 12;
Starting Out with C++, 3rd Edition
41
int whole = 12;
float real = 3.5;
cout << "In main the value of whole is " << whole < < endl;
cout << "and the value of real is " << real << endl ;
changeThem(whole, real); // Call changeThem with 2 a rguments
cout << "Now back in main again, the value of ";
cout << "whole is " << whole << endl;
cout << "and the value of real is " << real << endl ;
}
Program continues
//**************************************************************
// Definition of function changeThem. *
// It uses i, an int parameter, and f, a float. The values of *
// i and f are changed and then displayed. *
//**************************************************************
void changeThem(int i, float f)
Starting Out with C++, 3rd Edition
42
void changeThem(int i, float f)
{
i = 100;
f = 27.5;
cout << "In changeThem the value of i is changed to ";
cout << i << endl;
cout << "and the value of f is changed to " << f << endl;
}
Program Output
In main the value of whole is 12 and the value of real is 3.5In changeThem the value of i is changed to 100 and the value of f is changed to 27.5
Starting Out with C++, 3rd Edition
43
and the value of f is changed to 27.5Now back in main again, the value of whole is 12and the value of real is 3.5
Figure 6-7
Starting Out with C++, 3rd Edition
44
Person 6 (StevanyWuaten, Sinska)
Starting Out with C++, 3rd Edition
45
6.6 Focus on Software Engineering: Using Functions in a Menu-Driven Program
• Functions are ideal for use in menu-driven programs. When the user selects an item from a menu, the program can call the appropriate function.
Starting Out with C++, 3rd Edition
46
Program 6-10// This is a menu-driven program that makes a function call
// for each selection the user makes.
#include <iostream.h>
// Function Prototypes
void adult(int);
Starting Out with C++, 3rd Edition
47
void child(int);
void senior(int);
void main(void)
{
int choice, months;
Program continues
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
do
{
cout << " \ n\ t \ tHealth Club Membership Menu \ n\ n";
Starting Out with C++, 3rd Edition
48
cout << " \ n\ t \ tHealth 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";
cout << "Enter your choice: ";
cin >> choice;
Program continuesif (choice != 4)
{ cout << "For how many months? ";
cin >> months;
}
switch (choice)
{ case 1: adult(months);
break;
Starting Out with C++, 3rd Edition
49
break;
case 2: child(months);
break;
case 3: senior(months);
break;
case 4: cout << "Thanks for using this ";
cout << "program.\n";
break;
Program continuesdefault: cout << "The valid choices are 1-4. ";
cout << "Try again.\n";
}
} while (choice != 4);
}
//***********************************************************// Definition of function adult. Uses an integer pa rameter, mon. *
// mon holds the number of months the membership sh ould be *
Starting Out with C++, 3rd Edition
50
// calculated for. The cost of an adult membership for that many *
// months is displayed. *
//************************************************* *****************
void adult(int mon)
{
cout << "The total charges are $";
cout << (mon * 40.0) << endl;
}
Program continues//************************************************* *******************
// Definition of function child. Uses an integer pa rameter, mon. *
// mon holds the number of months the membership sh ould be *
// calculated for. The cost of a child membership f or that many *
// months is displayed. *
//*************************************************************
void child(int mon)
Starting Out with C++, 3rd Edition
51
void child(int mon)
{
cout << "The total charges are $";
cout << (mon * 20.0) << endl;
}
Program continues
//************************************************* ******************
// Definition of function senior. Uses an integer p arameter, mon. *
// mon holds the number of months the membership sh ould be *
// calculated for. The cost of a senior citizen mem bership for *
// that many months is displayed. *
Starting Out with C++, 3rd Edition
52
// that many months is displayed. *
//************************************************************
void senior(int mon)
{
cout << "The total charges are $";
cout << (mon * 30.0) << endl;
}
Program Output with Example InputHealth Club Membership Menu
1. Standard adult Membership
2. child Membership
3. senior Citizen Membership
4. Quit the Program
Enter your choice: 1
Starting Out with C++, 3rd Edition
53
For how many months 12
The total charges are $480.00
Health Club Membership Menu
1. Standard adult Membership
2. child Membership
3. senior Citizen Membership
4. Quit the Program
Enter your choice: 4
Thanks for using this program.
Person 7 (Helga, Destyani Maria)
Starting Out with C++, 3rd Edition
54
6.7 The return Statement
• The return statement causes a function to end immediately.
Starting Out with C++, 3rd Edition
55
Program 6-11// This program demonstrates a function with a return
statement.
#include <iostream.h>
// Function prototype
void halfway(void);
Starting Out with C++, 3rd Edition
56
void main(void)
{
cout << "In main, calling halfway...\n";
halfway();
cout << "Now back in main.\n";
}
Program continues
//*********************************************************
// Definition of function halfway. *
// This function has a return statement that forces it to *
// terminate before the last statement is executed. *
//*********************************************************
void halfway(void)
Starting Out with C++, 3rd Edition
57
void halfway(void)
{
cout << "In halfway now.\n";
return;
cout <<"Will you ever see this message?\n";
}
Program Output
In main, calling halfway...In halfway now.Now back in main.
Starting Out with C++, 3rd Edition
58
Program 6-12// This program uses a function to perform division. If division
// by zero is detected, the function returns.
#include <iostream.h>
// Function prototype.
void divide(float, float);
void main(void)
{
Starting Out with C++, 3rd Edition
59
float num1, num2;
cout << "Enter two numbers and I will divide the first\n";
cout << "number by the second number: ";
cin >> num1 >> num2;
divide(num1, num2);
}
Program continues//************************************************* ***************
// Definition of function divide. *
// Uses two parameters: arg1 and arg2. The function divides arg1 *
// by arg2 and shows the result. If arg2 is zero, h owever, the *
// function returns. *
//************************************************* ***************
void divide(float arg1, float arg2)
Starting Out with C++, 3rd Edition
60
void divide(float arg1, float arg2)
{
if (arg2 == 0.0)
{
cout << "Sorry, I cannot divide by zero.\n";
return;
}
cout << "The quotient is " << (arg1 / arg2) << endl ;
}
Program Output with Example Input
Enter two numbers and I will divide the firstnumber by the second number: 12 0 [Enter]Sorry, I cannot divide by zero.
Starting Out with C++, 3rd Edition
61
Person 8 (Widya, Erni)
Starting Out with C++, 3rd Edition
62
6.8 Returning a value From a Function
• A function may send a value back to the part of the program that called the function.
Starting Out with C++, 3rd Edition
63
Figure 6-10
Starting Out with C++, 3rd Edition
64
Program 6-13
// This program uses a function that returns a valu e.
#include <iostream.h>
//Function prototype
int square(int);
void main(void)
Starting Out with C++, 3rd Edition
65
void main(void)
{
int value, result;
cout << "Enter a number and I will square it: ";
cin >> value;
result = square(value);
cout << value << " squared is " << result << endl;
}
Program continues
//************************************************* ***
// Definition of function square. *
// This function accepts an int argument and return s *
// the square of the argument as an int. *
Starting Out with C++, 3rd Edition
66
//************************************************* ***
int square(int number)
{
return number * number;
}
Program Output with Example Input
Enter a number and I will square it: 20 [Enter]20 squared is 400
Starting Out with C++, 3rd Edition
67
Figure 6-11
result = square(value);
int square(int number)
20
Starting Out with C++, 3rd Edition
68
int square(int number){
return number * number;
}
Person 9 (Juliano, Kristian)
Starting Out with C++, 3rd Edition
69
6.9 Returning Boolean Values
• Function may return true or falsevalues.
Starting Out with C++, 3rd Edition
70
Program 6-15// This program uses a function that returns true o r false.
#include <iostream.h>
// Function prototype
bool isEven(int);
void main(void)
{
int val;
Starting Out with C++, 3rd Edition
71
cout << "Enter an integer and I will tell you ";
cout << "if it is even or odd: ";
cin >> val;
if (isEven(val))
cout << val << " is even.\n";
else
cout << val << " is odd.\n";
}
Program continues
//************************************************* ********************
// Definition of function isEven. This function acc epts an *
// integer argument and tests it to be even or odd. The function *
// returns true if the argument is even or false if the argument is *
// odd. *
// The return value is bool. *
//************************************************* ********************
bool isEven(int number)
{
Starting Out with C++, 3rd Edition
72
{
bool status;
if (number % 2)
status = false; // The number is odd if there's a r emainder.
else
status = true; // Otherwise, the number is even.
return status;
}
Program Output
Enter an integer and I will tell you if it is even or odd: 5 [Enter]
5 is odd.
Starting Out with C++, 3rd Edition
73
Person 10 (Supardi, Yan Makarunggala , Stefanny Tangkuman)
Starting Out with C++, 3rd Edition
74
6.10 Local and Global Variables
• A local variable is declared inside a function, and is not accessible outside the function.
Starting Out with C++, 3rd Edition
75
function.
• A global variable is declared outside all functions and is accessible in its scope.
Program 6-16
// This program shows that variables declared in a function
// are hidden from other functions.
#include <iostream.h>
void func(void); // Function prototype
Starting Out with C++, 3rd Edition
76
void main(void)
{
int num = 1;
cout << "In main, num is " << num << endl;
func();
cout << "Back in main, num is still " << num << end l;
}
Program continues//*********************************************************
// Definition of function func. *
// It has a local variable, num, whose initial value, 20, *
// is displayed. *
//*********************************************************
void func(void)
Starting Out with C++, 3rd Edition
77
void func(void)
{
int num = 20;
cout << "In func, num is " << num << endl;
}
Program Output
In main, num is 1In func, num is 20Back in main, num is still 1
Starting Out with C++, 3rd Edition
78
Figure 6-8
Function main
num = 1 This numvariable is only visible in function main .
Starting Out with C++, 3rd Edition
79
Function func
num = 20 This numvariable is only visible in function func .
Program 6-17// This program shows that a global variable is visible
// to all the functions that appear in a program after
// the variable's declaration.
#include <iostream.h>
void func(void); // Function prototype
int num = 2; // Global variable
Starting Out with C++, 3rd Edition
80
int num = 2; // Global variable
void main(void)
{
cout << "In main, num is " << num << endl;
func();
cout << "Back in main, num is " << num << endl;
}
Program continues
//*****************************************************
// Definition of function func. *
// func changes the value of the global variable num *
//*****************************************************
Starting Out with C++, 3rd Edition
81
void func(void)
{
cout << "In func, num is " << num << endl;
num = 50;
cout << "But, it is now changed to " << num << endl;
}
Program Output
In main, num is 2In func, num is 2But, it is now changed to 50Back in main, num is 50
Starting Out with C++, 3rd Edition
82
Back in main, num is 50
Program 6-18// This program shows that a global variable is visible
// to all the functions that appear in a program after
// the variable's declaration.
#include <iostream.h>
void func(void); // Function prototype
Starting Out with C++, 3rd Edition
83
void main(void)
{
cout << "In main, num is not visible!\n";
func();
cout << "Back in main, num still isn't visible!\n";
}
Program continues
int num = 2; // Global variable
//*****************************************************
// Definition of function func *
// func changes the value of the global variable num. *
Starting Out with C++, 3rd Edition
84
// func changes the value of the global variable num. *
//*****************************************************
void func(void)
{
cout << "In func, num is " << num << endl;
num = 50;
cout << "But, it is now changed to " << num << endl;
}
Program Output
In main, num is not visible!In func, num is 2But, it is now changed to 50Back in main, num still isn't visible!
Starting Out with C++, 3rd Edition
85
Back in main, num still isn't visible!
Global Variables are Initialized to Zero by Default
• Unless you explicitly initialize numeric global variables, they are automatically initialized to zero.
Starting Out with C++, 3rd Edition
86
initialized to zero.
• Global character variables are initialized to NULL, or ASCII code 0.
Program 6-19// This program has an uninitialized global variable.
#include <iostream.h>
int globalNum; // Global variable. Automatically set to zero.
void main(void)
{
Starting Out with C++, 3rd Edition
87
{
cout << "globalNum is " << globalNum << endl;
}
Program Output
globalNum is 0
Starting Out with C++, 3rd Edition
88
Local and Global Variables with the Same Name
• If a function has a local variable with the same name as a global variable, only the local variable can be seen by the function.
Starting Out with C++, 3rd Edition
89
local variable can be seen by the function.
Program 6-20// This program shows that when a local variable ha s the
// same name as a global variable, the function onl y sees
// the local variable.
#include <iostream.h>
// Function prototypes
void texas();
Starting Out with C++, 3rd Edition
90
void arkansas();
int cows = 10;
void main(void){
cout << "There are " << cows << " cows in main.\n";texas();arkansas();cout << "Back in main, there are " << cows << " cow s.\n";
}
Program continues
//******************************************
// Definition of function texas. *
// The local variable cows is set to 100. *
//******************************************
void texas(void)
{
int cows = 100;
Starting Out with C++, 3rd Edition
91
cout << "There are " << cows << " cows in texas.\n" ;
}
Program continues
//******************************************
// Definition of function arkansas. *
// The local variable cows is set to 50. *
//******************************************
Starting Out with C++, 3rd Edition
92
void arkansas(void)
{
int cows = 50;
cout << "There are " << cows << " cows in arkansas.\n";
}
Program Output
There are 10 cows in main.There are 100 cows in texas.There are 50 cows in arkansas.Back in main, there are 10 cows.
Starting Out with C++, 3rd Edition
93
Back in main, there are 10 cows.
Program 6-21// This program has local and global variables. In the function
// ringUpSale, there is a local variable named tax. There is
// also a global variable with the same name.
#include <iostream.h>
void ringUpSale(void); // Function prototype
Starting Out with C++, 3rd Edition
94
// Global Variables
const float taxRate = 0.06;
float tax, sale, total;
void main(void)
{
char again;
Program continues
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
do
{
ringUpSale();
cout << "Is there another item to be purchased? ";
cin >> again;
} while (again == 'y' || again == 'Y');
Starting Out with C++, 3rd Edition
95
tax = sale * taxRate;
total = sale + tax;
cout << "The tax for this sale is " << tax << endl;
cout << "The total is " << total << endl;
}
Program continues//************************************************* *****************
// Definition of function ringUpSale. *
// This function asks for the quantity and unit pri ce of an item. *
// It then calculates and displays the sales tax an d subtotal *
// for those items. *
//************************************************* *****************
void ringUpSale(void){
Starting Out with C++, 3rd Edition
96
{int qty;float unitPrice, tax, thisSale, subTotal;
cout << "Quantity: ";cin >> qty;cout << "Unit price: ";cin >> unitPrice;thisSale = qty * unitPrice; // Get the total unit p rice
Program continues
sale += thisSale; // Update global variable sale
tax = thisSale * taxRate; // Get sales tax for these items
subTotal = thisSale + tax; // Get subtotal for these items
cout << "Price for these items: " << thisSale << endl;
Starting Out with C++, 3rd Edition
97
cout << "Price for these items: " << thisSale << endl;
cout << "tax for these items: " << tax << endl;
cout<< "subTotal for these items: " << subTotal << endl;
}
Program Output with Example InputQuantity: 2 [Enter]Unit Price: 20.00 [Enter]Price for these items: 40.00tax for these items: 2.40subTotal for these items: 42.40Is there another item to be purchased? y [Enter]Quantity: 3 [Enter]
Starting Out with C++, 3rd Edition
98
Unit Price: 12.00 [Enter]Price for these items: 36.00tax for these items: 2.16subTotal for these items: 38.16Is there another item to be purchased? n [Enter]The tax for this sale is 4.56The total is 80.56
Be Careful With Global Variables
• It is tempting to make all your variables global. But don’t do it!
• Using global variables can cause problems.
Starting Out with C++, 3rd Edition
99
• Using global variables can cause problems.– It is harder to debug a program that uses global
variables
Person 11 (Niksen, Hermawan)
Starting Out with C++, 3rd Edition
100
6.11 Static Local Variables
• If a function is called more than once in a program, the values stored in the function’s local variables do not persist between
Starting Out with C++, 3rd Edition
101
local variables do not persist between function calls.
• To get a variable to keep it’s value even after the function ends, you must create static variables
Program 6-22// This program shows that local variables do not r etain
// their values between function calls.
#include <iostream.h>
// Function prototype
void showLocal(void);
Starting Out with C++, 3rd Edition
102
void showLocal(void);
void main(void)
{
showLocal();
showLocal();
}
Program continues
//***********************************************************
// Definition of function showLocal. *
// The initial value of localNum, which is 5, is displayed. *
// The value of localNum is then changed to 99 before the *
// function returns. *
//***********************************************************
Starting Out with C++, 3rd Edition
103
void showLocal(void)
{
int localNum = 5; // Local variable
cout << "localNum is " << localNum << endl;
localNum = 99;
}
Program Output
localNum is 5localNum is 5
Starting Out with C++, 3rd Edition
104
Program 6-23//This program uses a static local variable.#include <iostream.h>void showStatic(void); // Function prototype
void main(void){
for (int count = 0; count < 5; count++)showStatic();
}
//************************************************* ************// Definition of function showStatic. *
Starting Out with C++, 3rd Edition
105
// Definition of function showStatic. *// statNum is a static local variable. Its value is displayed *// and then incremented just before the function re turns. *//************************************************* ************
void showStatic(void){
static int statNum;
cout << "statNum is " << statNum << endl;statNum++;
}
Program Output
statNum is 0statNum is 1statNum is 2statNum is 3
Starting Out with C++, 3rd Edition
106
statNum is 3statNum is 4
Program 6-24// This program shows that a static local variable is only
// initialized once.
#include <iostream.h>
void showStatic(void); // Function prototype
void main(void)
Starting Out with C++, 3rd Edition
107
void main(void)
{
for (int count = 0; count < 5; count++)
showStatic();
}
Program continues
//***********************************************************
// Definition of function showStatic. *
// statNum is a static local variable. Its value is displayed
// and then incremented just before the function returns. *
//***********************************************************
Starting Out with C++, 3rd Edition
108
void showStatic()
{
static int statNum = 5;
cout << "statNum is " << statNum << endl;
statNum++;
}
Program Output
statNum is 5statNum is 6statNum is 7statNum is 8
Starting Out with C++, 3rd Edition
109
statNum is 8statNum is 9
Person 12 (Korinus, Eka P. Paputungan)
Starting Out with C++, 3rd Edition
110
6.12 Default Arguments
• Default arguments are passed to parameters automatically if no argument is provided in the function call.
Starting Out with C++, 3rd Edition
111
the function call.
• A function’s default arguments should be assigned in the earliest occurrence of the function name. This will usually mean the function prototype.
Program 6-25// This program demonstrates default function argum ents.
#include <iostream.h>
// Function prototype with default arguments
void displayStars(int = 10, int = 1);
void main(void)
{
Starting Out with C++, 3rd Edition
112
{
displayStars();
cout << endl;
displayStars(5);
cout << endl;
displayStars(7, 3);
}
Program continues
//************************************************* *************
// Definition of function displayStars. *
// The default argument for cols is 10 and for rows is 1. *
// This function displays a rectangle made of aster isks. *
//************************************************* *************
void displayStars(int cols, int rows)
{
Starting Out with C++, 3rd Edition
113
{
// Nested loop. The outer loop controls the rows
// and the inner loop controls the columns.
for (int down = 0; down < rows; down++)
{
for (int across = 0; across < cols; across++)
cout << "*";
cout << endl;
}
}
Program Output
**********
*****
Starting Out with C++, 3rd Edition
114
*******
*******
*******
Default Argument Summary
• The value of a default argument must be a constant (either a literal value of a named constant).
• When an argument is left out of a function call (because it has a default value), all the arguments that come after it must be left out too.
Starting Out with C++, 3rd Edition
115
must be left out too.• When a function has a mixture of parameters both with and
without default arguments, the parameters with default arguments must be declared last.
Person 13 (Yuyun, Ukasiah)
Starting Out with C++, 3rd Edition
116
6.13 Using Reference Variables as Parameters
• When used as parameters, reference variables allow a function to access the parameter’s original argument, changes to
Starting Out with C++, 3rd Edition
117
parameter’s original argument, changes to the parameter are also made to the argument.
Example:
void doubleNum(int &refVar)
{
refVar *= 2;
}
Starting Out with C++, 3rd Edition
118
}
// The variable refVar is called
// “a reference to an int”
Program 6-26// This program uses a reference variable as a function
// parameter.
#include <iostream.h>
// Function prototype. The parameter is a reference variable.
void doubleNum(int &);
void main(void)
Starting Out with C++, 3rd Edition
119
{
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;
}
Program continues
//************************************************************
// Definition of doubleNum. *
// The parameter refVar is a reference variable. The value *
// in refVar is doubled. *
//************************************************************
Starting Out with C++, 3rd Edition
120
//************************************************************
void doubleNum (int &refVar)
{
refVar *= 2;
}
Program Output
In main, value is 4Now calling doubleNum...Now back in main. value is 8
Starting Out with C++, 3rd Edition
121
Program 6-27// This program uses reference variables as function
// parameters.
#include <iostream.h>
// Function prototypes. Both functions use reference variables
// as parameters
void doubleNum(int &);
void getNum(int &);
Starting Out with C++, 3rd Edition
122
void main(void)
{
int value;
getNum(value);
doubleNum(value);
cout << "That value doubled is " << value << endl;
}
Program continues
//*************************************************************
// Definition of getNum. *
// The parameter userNum is a reference variable. The user is *
// asked to enter a number, which is stored in userNum. *
//*************************************************************
void getNum(int &userNum)
Starting Out with C++, 3rd Edition
123
void getNum(int &userNum)
{
cout << "Enter a number: ";
cin >> userNum;
}
Program continues
//************************************************************
// Definition of doubleNum. *
// The parameter refVar is a reference variable. The value *
// in refVar is doubled. *
//************************************************************
Starting Out with C++, 3rd Edition
124
//************************************************************
void doubleNum (int &refVar)
{
refVar *= 2;
}
Program Output with Example Input
Enter a number: 12 [Enter]That value doubled is 24
Starting Out with C++, 3rd Edition
125
Reference Argument Warning
• Don’t get carried away with using reference variables as function parameters. Any time you allow a function to alter a variable
Starting Out with C++, 3rd Edition
126
you allow a function to alter a variable that’s outside the function, you are creating potential debugging problems. Reference variables should only be used as parameters when the situation demands them.
Person 14 (Serly, Denny)
Starting Out with C++, 3rd Edition
127
6.14 Overloaded Functions
• Two or more functions may have the same name as long as their parameter lists are different.
Starting Out with C++, 3rd Edition
128
different.
Program 6-28#include <iostream.h>
// Function prototypes
int square(int);
float square(float);
void main(void)
{
int userInt;
Starting Out with C++, 3rd Edition
129
int userInt;
float userFloat;
cout.precision(2);
cout << "Enter an integer and a floating-point valu e: ";
cin >> userInt >> userFloat;
cout << "Here are their squares: ";
cout << square(userInt) << " and " << square(userFl oat);
}
Program continues
// Definition of overloaded function square.
// This function uses an int parameter, number. It returns the
// square of number as an int.
int square(int number)
{
return number * number;
}
Starting Out with C++, 3rd Edition
130
}
// Definition of overloaded function square.
// This function uses a float parameter, number. It returns the
// square of number as a float.
float square(float number)
{
return number * number;
}
Program Output with Example Input
Enter an integer and floating-point value: 12 4.2 [Enter]
Here are their squares: 144 and 17.64
Starting Out with C++, 3rd Edition
131
Program 6-29// This program demonstrates overloaded functions t o calculate// the gross weekly pay of hourly-paid or salaried employees.#include <iostream.h>
// Function prototypesvoid getChoice(char &);float calcWeeklyPay(int, float);float calcWeeklyPay(float);
void main(void){
Starting Out with C++, 3rd Edition
132
{char selection;int worked;float rate, yearly;
cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << “Do you want to calculate the weekly pay of \n";cout << “(H) an hourly-paid employee, or \n”;cout << “(S) a salaried employee?\n”;
Program continuesgetChoice(selection);
switch (selection)
{
case ‘H’ :
case ‘h’ : cout << “How many hours were worked? “;
cin >> worked;
cout << “What is the hour pay rate? “;
cin >> rate;
cout << “The gross weekly pay is “;
Starting Out with C++, 3rd Edition
133
cout << “The gross weekly pay is “;
cout << calcWeeklyPay(worked, rate);
break;
case ‘S’ :
case ‘s’ : cout << “What is the annual salary? “;
cin >> yearly;
cout << “The gross weekly pay is “;
cout << calcWeeklyPay(yearly);
break;
}
}
Program continues//***********************************************************
// Definition of function getChoice. *
// The parameter letter is a reference to a char. *
// This function asks the user for an H or an S and returns *
// the validated input. *
//***********************************************************
void getChoice(char &letter){
Starting Out with C++, 3rd Edition
134
{do{
cout << “Enter your choice (H or S): “;cin >> letter;
} while (letter != ‘H’ && letter != ‘h’ &&letter != ‘S’ && letter != ‘s’);
}
Program continues//***********************************************************
// Definition of overloaded function calcWeeklyPay. *
// This function calculates the gross weekly pay of *
// an hourly-paid employee. The parameter hours hold the *
// hourly pay rate. The function returns the weekly salary. *
//***********************************************************
void calcWeekly(int hours, float payRate)
Starting Out with C++, 3rd Edition
135
void calcWeekly(int hours, float payRate)
{
return hours * payRate;
}
Program continues//***********************************************************
// Definition of overloaded function calcWeeklyPay. *
// This function calculates the gross weekly pay of *
// a salaried employee. The parameter holds the employee’s *
// annual salary. The function returns the weekly salary. *
//***********************************************************
void calcWeekly(float annSalary)
Starting Out with C++, 3rd Edition
136
void calcWeekly(float annSalary)
{
return annSalary / 52.0;
}
Program Output with Example InputDo you want to calculate the weekly pay of
(H) an houly-paid employee, or
(S) a salaried employee? H[Enter]
How many hours were worked? 40[Enter]
What is the hour pay rate? 18.50[Enter]
The gross weekly pay is 740.00
Starting Out with C++, 3rd Edition
137
Program Output with Other Example InputDo you want to calculate the weekly pay of
(H) an houly-paid employee, or
(S) a salaried employee? S[Enter]
What is the annual salary? 48000.00[Enter]
The gross weekly pay is 923.08
Person 15 (Relvando, Gladis Ansiga)
Starting Out with C++, 3rd Edition
138
6.15 The exit() Function
• The exit() function causes a program to terminate, regardless of which function or control mechanism is executing.
Starting Out with C++, 3rd Edition
139
control mechanism is executing.
Program 6-30// This program shows how the exit function causes a program
// to stop executing.
#include <iostream.h>
#include <stdlib.h> // For exit
void function(void); // Function prototype
Starting Out with C++, 3rd Edition
140
void function(void); // Function prototype
void main(void)
{
function();
}
Program continues
//***********************************************************
// This function simply demonstrates that exit can be used *
// to terminate a program from a function other than main. *
//***********************************************************
Starting Out with C++, 3rd Edition
141
void function(void)
{
cout << "This program terminates with the exit function.\n";
cout << "Bye!\n";
exit(0);
cout << "This message will never be displayed\n";
cout << "because the program has already terminated.\n";
}
Program Output
This program terminates with the exit function.Bye!
Starting Out with C++, 3rd Edition
142
Program 6-31// This program demonstrates the exit function.
#include <iostream.h>
#include <stdlib.h> // For exit
void main(void)
{
char response;
Starting Out with C++, 3rd Edition
143
cout << "This program terminates with the exit func tion.\n";
cout << "Enter S to terminate with the EXIT_SUCCESS code\n";
cout << "or f to terminate with the EXIT_FAILURE co de: ";
cin >> response;
Program continues
if (response == 'S')
{
cout << "Exiting with EXIT_SUCCESS.\n";
exit(EXIT_SUCCESS);
}
else
{
Starting Out with C++, 3rd Edition
144
{
cout << "Exiting with EXIT_FAILURE.\n";
exit(EXIT_FAILURE);
}
}
Program Output with Example InputThis program terminates with the exit function.Enter S to terminate with the EXIT_SUCCESS codeor f to terminate with the EXIT_FAILURE code: s [Enter]Exiting with EXIT_SUCCESS.
Program Output With Other Example Input
Starting Out with C++, 3rd Edition
145
Program Output With Other Example InputThis program terminates with the exit function.Enter S to terminate with the EXIT_SUCCESS codeor f to terminate with the EXIT_FAILURE code: f [Enter]Exiting with EXIT_FAILURE.
Person 16 (Johra, Andika)
Starting Out with C++, 3rd Edition
146
6.16 Stubs and Drivers
• Stubs and drivers are very helpful tools for testing and debugging programs that use functions.
Starting Out with C++, 3rd Edition
147
functions.
• A stub is a dummy function that is called instead of the actual function it represents.
• A driver is a program that tests a function by simply calling it.
// Stub for the adult function.
void adult(int months)
{
cout << "The function adult was called with " << mo nths;
cout << " as its argument.\n";
}
// Stub for the child function.
void child(int months)
{
cout << "The function child was called with " << mo nths;
cout << " as its argument. \ n";
Starting Out with C++, 3rd Edition
148
cout << " as its argument. \ n";
}
// Stub for the senior function.
void senior(int months)
{
cout << "The function senior was called with " << m onths;
cout << " as its argument.\n";
}
Person 17 (Kevin, Jonathan Tompodung, Abdulharis)
Starting Out with C++, 3rd Edition
149
Functions and subprograms
• The Top-down design appeoach is based on dividing the main problem into smaller tasks which may be divided into simpler tasks, then implementing each simple task by a subprogram or a function
• A C++ function or a subprogram is simply a chunk of C++
Starting Out with C++, 3rd Edition
150
• A C++ function or a subprogram is simply a chunk of C++ code that has– A descriptive function name, e.g.
•• computeTaxescomputeTaxes to compute the taxes for an employee •• isPrimeisPrime to check whether or not a number is a prime number
– A returning value• The computeTaxesomputeTaxes function may return with a double number
representing the amount of taxes• The isPrimeisPrime function may return with a Boolean value (true or false)
C++ Standard Functions
• C++ language is shipped with a lot of functions which are known as standard functions
• These standard functions are groups in different libraries which can be included in the C++ program, e.g.
Starting Out with C++, 3rd Edition
151
libraries which can be included in the C++ program, e.g.– Math functions are declared in <math.h> library– Character-manipulation functions are declared in
<ctype.h> library– C++ is shipped with more than 100 standard libraries,
some of them are very popular such as <iostream.h> and <stdlib.h>, others are very specific to certain hardware platform, e.g. <limits.h> and <largeInt.h>
Example of Using Standard C++ Math Functions
#include <iostream.h>#include <math.h>void main(){
Starting Out with C++, 3rd Edition
152
// Getting a double valuedouble x;cout << "Please enter a real number: ";cin >> x;// Compute the ceiling and the floor of the real numbercout << "The ceil(" << x << ") = " << ceil(x) << endl;cout << "The floor(" << x << ") = " << floor(x) << endl;
}
Example of Using Standard C++ Character Functions
#include <iostream.h> // input/output handling#include <ctype.h> // character type functionsvoid main(){
char ch;cout << "Enter a character: ";
Explicit casting
Starting Out with C++, 3rd Edition
153
cin >> ch; cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;if (isdigit(ch))
cout << "'" << ch <<"' is a digit!\n";else
cout << "'" << ch <<"' is NOT a digit!\n";}
User-Defined C++ Functions
• Although C++ is shipped with a lot of standard functions, these functions are not enough for all users, therefore, C++ provides its users with a way to define their own functions (or user-defined
Starting Out with C++, 3rd Edition
154
to define their own functions (or user-defined function)
• For example, the <math.h> library does not include a standard function that allows users to round a real number to the ith digits, therefore, we must declare and implement this function ourselves
How to define a C++ Function?
• Generally speaking, we define a C++ function in two steps (preferably but not mandatory)
Starting Out with C++, 3rd Edition
155
mandatory)– Step #1 – declare the function signaturefunction signature in
either a header file (.h file) or before the main function of the program
– Step #2 – Implement the function in either an implementation file (.cpp) or after the main function
What is The Syntactic Structure of a C++ Function?
• A C++ function consists of two parts– The function header, and
– The function body
Starting Out with C++, 3rd Edition
156
– The function body
• The function header has the following syntax
<return value> <name> (<parameter <return value> <name> (<parameter list>)list>)
• The function body is simply a C++ code enclosed between { }
Example of User-definedC++ Function
double computeTax(double income)
Starting Out with C++, 3rd Edition
157
double computeTax(double income){
if (income < 5000.0) return 0.0;double taxes = 0.07 * (income-5000.0);return taxes;
}
double computeTax(double income)
Example of User-definedC++ Function
Function header
Starting Out with C++, 3rd Edition
158
double computeTax(double income){
if (income < 5000.0) return 0.0;double taxes = 0.07 * (income-5000.0);return taxes;
}
Example of User-definedC++ Function
double computeTax(double income)
Function header
Function body
Starting Out with C++, 3rd Edition
159
double computeTax(double income){
if (income < 5000.0) return 0.0;double taxes = 0.07 * (income-5000.0);return taxes;
}
Function Signature
• The function signature is actually similar to the function header except in two aspects:– The parameters’ names may not be specified in
the function signature
Starting Out with C++, 3rd Edition
160
the function signature– The function signature must be ended by a
semicolon
• Example
double computeTaxes(double) ;
Unnamed Parameter
Semicolon;
Why Do We Need Function Signature?
• For Information Hiding– If you want to create your own library and share it with
your customers without letting them know the implementation details, you should declare all the function signatures in a header (.h) file and distribute
Starting Out with C++, 3rd Edition
161
function signatures in a header (.h) file and distribute the binary code of the implementation file
• For Function Abstraction– By only sharing the function signatures, we have the
liberty to change the implementation details from time to time to
• Improve function performance• make the customers focus on the purpose of the function, not
its implementation
Example#include <iostream>#include <string>using namespace std;
// Function Signaturedouble getIncome(string); double computeTaxes(double);void printTaxes(double);
double computeTaxes(double income){
if (income<5000) return 0.0;return 0.07*(income-5000.0);
}
double getIncome(string prompt){
cout << prompt;
Starting Out with C++, 3rd Edition
162
void main(){
// Get the income;double income = getIncome("Please enter the employee income: ");
// Compute Taxesdouble taxes = computeTaxes(income);
// Print employee taxesprintTaxes(taxes);
}
double income;cin >> income;
return income;}
void printTaxes(double taxes){
cout << "The taxes is $" << taxes << endl;}
Person 18 (Andrew, DesyKaseger)
Starting Out with C++, 3rd Edition
163
Building Your Libraries
• It is a good practice to build libraries to be used by you and your customers
• In order to build C++ libraries, you should be familiar with
Starting Out with C++, 3rd Edition
164
• In order to build C++ libraries, you should be familiar with– How to create header files to store function
signatures– How to create implementation files to store
function implementations– How to include the header file to your program
to use your user-defined functions
C++ Header Files
• The C++ header files must have .h extension and should have the following structure– #ifndef compiler directive
Starting Out with C++, 3rd Edition
165
– #ifndef compiler directive– #define compiler directive– May include some other header files– All functions signatures with some comments
about their purposes, their inputs, and outputs– #endif compiler directive
TaxesRules Header file
#ifndef _TAXES_RULES_#define _TAXES_RULES_
#include <iostream>#include <string>using namespace std;
double computeTaxes(double);// purpose -- to compute the taxes for a
given income// input -- a double value representing
the income// output -- a double value representing
Starting Out with C++, 3rd Edition
166
using namespace std;
double getIncome(string); // purpose -- to get the employee
income// input -- a string prompt to be
displayed to the user// output -- a double value representing
the income
// output -- a double value representing the taxes
void printTaxes(double);// purpose -- to display taxes to the user// input -- a double value representing
the taxes// output -- None
#endif
TaxesRules Implementation File
#include "TaxesRules.h"
double computeTaxes(double income){
if (income<5000) return 0.0;return 0.07*(income-5000.0);
void printTaxes(double taxes){
cout << "The taxes is $" << taxes
Starting Out with C++, 3rd Edition
167
return 0.07*(income-5000.0);}
double getIncome(string prompt){
cout << prompt;double income;cin >> income;return income;
}
cout << "The taxes is $" << taxes << endl;
}
Main Program File
#include "TaxesRules.h"void main(){
// Get the income;
Starting Out with C++, 3rd Edition
168
double income = getIncome("Please enter the employee income: ");
// Compute Taxesdouble taxes = computeTaxes(income);
// Print employee taxesprintTaxes(taxes);
}
Inline Functions
• Sometimes, we use the keyword inline inline to define user-defined functions – Inline functions are very small functions, generally, one
or two lines of code
Starting Out with C++, 3rd Edition
169
or two lines of code– Inline functions are very fast functions compared to the
functions declared without the inline keyword
• Exampleinlineinline double degrees( double radian)
{return radian * 180.0 / 3.1415;
}
Example #1• Write a function to test if a number is an odd
number
inline bool odd (int x)
Starting Out with C++, 3rd Edition
170
inline bool odd (int x)
{
return (x % 2 == 1);
}
Example #2
• Write a function to compute the distance between two points (x1, y1) and (x2, y2)
Starting Out with C++, 3rd Edition
171
Inline double distance (double x1, double y1,
double x2, double y2)
{
return sqrt(pow(x1-x2,2)+pow(y1-y2,2));
}
Example #3
• Write a function to compute n!
int factorial( int n)
Starting Out with C++, 3rd Edition
172
int factorial( int n){
int product=1;for (int i=1; i<=n; i++) product *= i;return product;
}
Example #4Function Overloading
• Write functions to return with the maximum number of two numbers
inline int max( int x, int y){
An overloaded function is a
function that is defined more
Starting Out with C++, 3rd Edition
173
{if (x>y) return x; else return y;
}
inline double max( double x, double y){
if (x>y) return x; else return y;}
defined more than once with different data
types or different
number of parameters
Person 19 (Arley, Arthur Toliu)
Starting Out with C++, 3rd Edition
174
Sharing Data Among User-Defined Functions
• There are two ways to share data among different functions– Using global variables (very bad practice!)
Starting Out with C++, 3rd Edition
175
– Passing data through function parameters• Value parameters
• Reference parameters
• Constant reference parameters
C++ Variables
• A variable is a place in memory that has– A name or identifier (e.g. income, taxes, etc.)– A data type (e.g. int, double, char, etc.)– A size (number of bytes)
Starting Out with C++, 3rd Edition
176
– A size (number of bytes)– A scope (the part of the program code that can use it)
• Global variables – all functions can see it and using it• Local variables – only the function that declare local variables
see and use these variables
– A life time (the duration of its existence)• Global variables can live as long as the program is executed• Local variables are lived only when the functions that define
these variables are executed
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
Starting Out with C++, 3rd Edition
177
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
x 0
Starting Out with C++, 3rd Edition
178
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
x 0
Starting Out with C++, 3rd Edition
179
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}
void main()void main(){ {
f2();f2();cout << x << cout << x <<
endl ;endl ;}}
1
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
x 04
Starting Out with C++, 3rd Edition
180
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}
void main()void main(){ {
f2();f2();cout << x << cout << x <<
endl ;endl ;}}
1
void f2()void f2(){ {
x += 4;x += 4;f1();f1();
}}
2
45
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
x
void f1()void f1(){ {
x++;x++;}}
4
Starting Out with C++, 3rd Edition
181
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}
void main()void main(){ {
f2();f2();cout << x << cout << x <<
endl ;endl ;}}
1
void f2()void f2(){ {
x += 4;x += 4;f1();f1();
}}
3
}}
45
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
x
void f1()void f1(){ {
x++;x++;}}
5
Starting Out with C++, 3rd Edition
182
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}
void main()void main(){ {
f2();f2();cout << x << cout << x <<
endl;endl;}}
1
void f2()void f2(){ {
x += 4;x += 4;f1();f1();
}}
3
}}
45
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
x
Starting Out with C++, 3rd Edition
183
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}
void main()void main(){ {
f2();f2();cout << x << cout << x <<
endl;endl;}}
1
void f2()void f2(){ {
x += 4;x += 4;f1();f1();
}}6
45
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
x
Starting Out with C++, 3rd Edition
184
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}void main()void main(){ {
f2();f2();cout << x << cout << x <<
endl;endl;}}
7
45
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
x
Starting Out with C++, 3rd Edition
185
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}void main()void main(){ {
f2();f2();cout << x << cout << x <<
endl;endl;}}
8
I. Using Global Variables
#include <iostream.h>int x = 0;void f1() { x++; }void f2() { x+=4; f1(); }
Starting Out with C++, 3rd Edition
186
void f2() { x+=4; f1(); }void main(){
f2();cout << x << endl;
}
What Happens When We Use Inline Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
Starting Out with C++, 3rd Edition
187
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
What Happens When We Use Inline Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
0x
The inline keyword instructs the
compiler to replace
Starting Out with C++, 3rd Edition
188
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
void main()void main(){ {
x+=4;x+=4;x++;x++;cout << x << endl;cout << x << endl;
}}
1
compiler to replace the function call with the function
body!
What Happens When We Use Inline Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
4x
Starting Out with C++, 3rd Edition
189
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
void main()void main(){ {
x+=4;x+=4;x++;x++;cout << x << endl;cout << x << endl;
}}
2
What Happens When We Use Inline Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
5x
Starting Out with C++, 3rd Edition
190
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
void main()void main(){ {
x+=4;x+=4;x++;x++;cout << x << endl;cout << x << endl;
}}
3
What Happens When We Use Inline Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
5x
Starting Out with C++, 3rd Edition
191
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
void main()void main(){ {
x+=4;x+=4;x++;x++;cout << x << endl;cout << x << endl;
}}
4
What Happens When We Use Inline Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
Starting Out with C++, 3rd Edition
192
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
Person 20 (Masita Adam, Jonathan Tasyam)
Starting Out with C++, 3rd Edition
193
What is Bad About UsingGlobal Vairables?
• Not safe!– If two or more programmers are working together in a
program, one of them may change the value stored in the global variable without telling the others who may
Starting Out with C++, 3rd Edition
194
the global variable without telling the others who may depend in their calculation on the old stored value!
• Against The Principle of Information Hiding!– Exposing the global variables to all functions is against
the principle of information hiding since this gives all functions the freedom to change the values stored in the global variables at any time (unsafe!)
Local Variables
• Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit
• You have to initialize the local variable before
Starting Out with C++, 3rd Edition
195
• You have to initialize the local variable before using it
• If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
Starting Out with C++, 3rd Edition
196
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
x 0
Global variables are automatically initialized to
0
Starting Out with C++, 3rd Edition
197
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
x 0
Starting Out with C++, 3rd Edition
198
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun();fun();cout << x << cout << x <<
endl;endl;
1
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
x 4
void fun()void fun()
x ????
Starting Out with C++, 3rd Edition
199
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun();fun();cout << x << cout << x <<
endl;endl;
2
{ { int x = 10;int x = 10;cout << x << cout << x <<
endl;endl;}}
x ????
3
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
x 4
void fun()void fun()
x 10
Starting Out with C++, 3rd Edition
200
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun();fun();cout << x << cout << x <<
endl;endl;
2
{ { int x = 10;int x = 10;cout << x << cout << x <<
endl;endl;}}
x 10
3
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
x = 4;
x 4
void fun()void fun()
x 10
Starting Out with C++, 3rd Edition
201
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun();fun();cout << x << cout << x <<
endl;endl;
2
{ { int x = 10;int x = 10;cout << x << cout << x <<
endl;endl;}}
x 10
4
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
x = 4;
x 4
void fun()void fun()
x 10
Starting Out with C++, 3rd Edition
202
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun();fun();cout << x << cout << x <<
endl;endl;
2
{ { int x = 10;int x = 10;cout << x << cout << x <<
endl;endl;}}
x 10
5
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
x = 4;
x 4
Starting Out with C++, 3rd Edition
203
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun();fun();cout << x << cout << x <<
endl;endl;
6
Example of Defining and Using Global and Local Variables
#include <iostream.h>int x; // Global variable// Global variableVoid fun(); // function signature// function signature
void main(){
x = 4;
x 4
Starting Out with C++, 3rd Edition
204
x = 4;fun();cout << x << endl;
}
void fun(){
int x = 10; // Local variable// Local variablecout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun();fun();cout << x << cout << x <<
endl;endl;
7
II. Using Parameters• Function Parameters come in three flavors:
–– Value parameters Value parameters – which copy the values of the function arguments
–– Reference parametersReference parameters – which refer to the function arguments by other local names and have the
Starting Out with C++, 3rd Edition
205
arguments by other local names and have the ability to change the values of the referenced arguments
–– Constant reference parametersConstant reference parameters – similar to the reference parameters but cannot change the values of the referenced arguments
Person 21 (Jayadi Kasenda, Rizky Rajamuda,, Imelda Florensia)
Starting Out with C++, 3rd Edition
206
Value Parameters• This is what we use to declare in the function signature or
function header, e.g.
int max (int x, int y);– Here, parameters x and y are value parameters– When you call the max function as max(4, 7)max(4, 7), the values 4 and 7 are
Starting Out with C++, 3rd Edition
207
– When you call the max function as max(4, 7)max(4, 7), the values 4 and 7 are copied to x and y respectively
– When you call the max function as max (a, b),max (a, b), where a=40 and b=10, the values 40 and 10 are copied to x and y respectively
– When you call the max function as max( a+b, b/2),max( a+b, b/2), the values 50 and 5 are copies to x and y respectively
• Once the value parameters accepted copies of the corresponding arguments data, they act as local variables!
Example of Using Value Parameters and Global Variables
#include <iostream.h>int x; // Global variable// Global variablevoid fun(int x){
cout << x << endl;x=x+5;
x 0
Starting Out with C++, 3rd Edition
208
x=x+5;}void main(){
x = 4;fun(x/2+1);cout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun(x/2+1);fun(x/2+1);cout << x << cout << x <<
endl;endl;
1
Example of Using Value Parameters and Global Variables
#include <iostream.h>int x; // Global variable// Global variablevoid fun(int x){
cout << x << endl;x=x+5;
x 4
void fun(int x void fun(int x
Starting Out with C++, 3rd Edition
209
x=x+5;}void main(){
x = 4;fun(x/2+1);cout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun(x/2+1);fun(x/2+1);cout << x << cout << x <<
endl;endl;
2
void fun(int x void fun(int x )){ {
cout << x << cout << x << endl;endl;
x=x+5;x=x+5;}} 3
3
Example of Using Value Parameters and Global Variables
#include <iostream.h>int x; // Global variable// Global variablevoid fun(int x){
cout << x << endl;x=x+5;
x 4
void fun(int x void fun(int x 38
Starting Out with C++, 3rd Edition
210
x=x+5;}void main(){
x = 4;fun(x/2+1);cout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun(x/2+1);fun(x/2+1);cout << x << cout << x <<
endl;endl;
2
void fun(int x void fun(int x )){ {
cout << x << cout << x << endl;endl;
x=x+5;x=x+5;}}
3
4
8
Example of Using Value Parameters and Global Variables
#include <iostream.h>int x; // Global variable// Global variablevoid fun(int x){
cout << x << endl;x=x+5;
x 4
void fun(int x void fun(int x 38
Starting Out with C++, 3rd Edition
211
x=x+5;}void main(){
x = 4;fun(x/2+1);cout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun(x/2+1);fun(x/2+1);cout << x << cout << x <<
endl;endl;
2
void fun(int x void fun(int x )){ {
cout << x << cout << x << endl;endl;
x=x+5;x=x+5;}}
38
5
Example of Using Value Parameters and Global Variables
#include <iostream.h>int x; // Global variable// Global variablevoid fun(int x){
cout << x << endl;x=x+5;
x 4
Starting Out with C++, 3rd Edition
212
x=x+5;}void main(){
x = 4;fun(x/2+1);cout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun(x/2+1);fun(x/2+1);cout << x << cout << x <<
endl;endl;
6
Example of Using Value Parameters and Global Variables
#include <iostream.h>int x; // Global variable// Global variablevoid fun(int x){
cout << x << endl;x=x+5;
x 4
Starting Out with C++, 3rd Edition
213
x=x+5;}void main(){
x = 4;fun(x/2+1);cout << x << endl;
}
void main()void main(){ {
x = 4;x = 4;fun(x/2+1);fun(x/2+1);cout << x << cout << x <<
endl;endl;
7
Reference Parameters
• As we saw in the last example, any changes in the value parameters don’t affect the original function arguments
• Sometimes, we want to change the values of the original function arguments or return with more
Starting Out with C++, 3rd Edition
214
• Sometimes, we want to change the values of the original function arguments or return with more than one value from the function, in this case we use reference parameters– A reference parameter is just another name to the
original argument variable– We define a reference parameter by adding the & in
front of the parameter name, e.g.
double update (double & & x);
Example of Reference Parameters
#include <iostream.h>void fun(int &y){
cout << y << endl;
Starting Out with C++, 3rd Edition
215
y=y+5;}void main(){
int x = 4; // Local variable// Local variablefun(x);cout << x << endl;
}
void main()void main(){ {
int x = 4;int x = 4;fun(x);fun(x);cout << x << cout << x <<
endl;endl;
1 x? x4
Example of Reference Parameters
#include <iostream.h>void fun(int &y){
cout << y << endl;y=y+5;
}void fun( int & y void fun( int & y ))
Starting Out with C++, 3rd Edition
216
}void main(){
int x = 4; // Local variablefun(x);cout << x << endl;
}
void main()void main(){ {
int x = 4;int x = 4;fun(x);fun(x);cout << x << cout << x <<
endl;endl;
2x? x4
)){ {
cout<<y<<endl;cout<<y<<endl;y=y+5;y=y+5;
}}
3
Example of Reference Parameters
#include <iostream.h>void fun(int &y){
cout << y << endl;y=y+5;
}void fun( int & y void fun( int & y ))
Starting Out with C++, 3rd Edition
217
}void main(){
int x = 4; // Local variablefun(x);cout << x << endl;
}
void main()void main(){ {
int x = 4;int x = 4;fun(x);fun(x);cout << x << cout << x <<
endl;endl;
2x? x4
)){ {
cout<<y<<endl;cout<<y<<endl;y=y+5;y=y+5;
}}
4 9
Example of Reference Parameters
#include <iostream.h>void fun(int &y){
cout << y << endl;y=y+5;
}void fun( int & y void fun( int & y ))
Starting Out with C++, 3rd Edition
218
}void main(){
int x = 4; // Local variablefun(x);cout << x << endl;
}
void main()void main(){ {
int x = 4;int x = 4;fun(x);fun(x);cout << x << cout << x <<
endl;endl;
2x? x9
)){ {
cout<<y<<endl;cout<<y<<endl;y=y+5;y=y+5;
}}
5
Example of Reference Parameters
#include <iostream.h>void fun(int &y){
cout << y << endl;y=y+5;
}
Starting Out with C++, 3rd Edition
219
}void main(){
int x = 4; // Local variablefun(x);cout << x << endl;
}
void main()void main(){ {
int x = 4;int x = 4;fun(x);fun(x);cout << x << cout << x <<
endl;endl;
6
x? x9
Example of Reference Parameters
#include <iostream.h>void fun(int &y){
cout << y << endl;y=y+5;
}
Starting Out with C++, 3rd Edition
220
}void main(){
int x = 4; // Local variablefun(x);cout << x << endl;
}
void main()void main(){ {
int x = 4;int x = 4;fun(x);fun(x);cout << x << cout << x <<
endl;endl;
x? x9
7
Constant Reference Parameters• Constant reference parameters are used under the
following two conditions:– The passed data are so big and you want to save time and
computer memory– The passed data will not be changed or updated in the
function body
Starting Out with C++, 3rd Edition
221
function body• For example
void report (constconststring && prompt);• The only valid arguments accepted by reference
parameters and constant reference parameters are variable names– It is a syntax error to pass constant values or expressions to
the (const) reference parameters