CS102 Introduction to Computer Programming

Download Report

Transcript CS102 Introduction to Computer Programming

CS102
Introduction to Computer
Programming
Chapter 6 Functions
Part I
Chapter 6 Topics
•
•
•
•
•
•
•
•
•
•
•
•
Breaking Up Your Programs
Defining and Calling a Function
Function Prototypes
Sending Information to a Function
Changing the value of a parameter
Functions and Menus
The return Statement
Returning a value from a Function
Returning Boolean Values
Local Variables
Global Variables
Local and Global Variables with the Same Name
Breaking Up Your Programs
• A function is a collection of statements that
performs a specific task
• Functions break programs up into small
manageable units
• Functions simplify programs by letting a set
of statements to be used multiple times
Concept - Programs may be broken up into smaller manageable
functions
Defining a Function
• Return Type: specify the type of the data that is to
be returned by the function
• Name: give functions descriptive names
• Parameter list: list the variables that hold the
values being sent to the function
• Body: statements that perform the function's
operations and are enclosed in braces.
Return type
Braces
void main(void)
Parameter List
{
Name
Body
cout << " Hello world";
}
Calling a Function
• Function call syntax
function_name();
• A function call may be placed in any flow
control structure (if, switch and loops)
• A program may have multiple function calls
– A function may also call a function.
• The compiler must know the number of
parameters and their type before the
function can be called
Concept - A function call is a statement that causes a function to
execute.
Program 6-1
#include <iostream.h>
// Definition of function
DisplayMessage.
// This function displays a greeting.
void DisplayMessage(void)
{
cout << "Hello from the function
DisplayMessage.\n";
}
4
5
DisplayMessage.
1
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
2
3
6
Back in function main
again.
Program 6-2
#include <iostream.h>
void DisplayMessage(void)
{
cout << "Hello from the function
DisplayMessage.\n";
}
void main(void)
{
cout << "Hello from main.\n";
for (int Count = 0; Count < 5;
Count++)
// Call DisplayMessage
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.
Hello from the function
DisplayMessage.
Hello from the function
DisplayMessage.
Back in function main
again.
Program 6-3
void main(void)
// This program has three functions:
main, First, and Second.
{
#include <iostream.h>
cout << "I am starting in function
// Definition of function First.
main.\n";
// This function displays a message.
First();
// Call function First
void First(void)
Second(); // Call function
Second
{
cout << "Back in function main
cout << "I am now inside the
again.\n";
function First.\n";
}
}
// Definition of function Second. This
function displays a message.
Program Output
void Second(void)
I am starting in function main.
{
I am now inside the function First.
cout << "I am now inside the
I am now inside the function Second
function Second.\n";
Back in function main again.
}
/* This program has three functions:
main, Deep, and Deeper*/
#include <iostream.h>
// Definition of function Deeper. This
function displays a message.*/
void Deeper(void)
{
cout << "I am now inside the
function Deeper.\n";
}
/* Definition of function Deep. This
function calls the function Deeper.*/
void Deep(void)
{
cout << "I am now inside the
function Deep.\n";
Deeper();
// Call function
Deeper
cout << "Now I am back in Deep.\n";
}
Program 6-4
void main(void)
{
cout << "I am starting in function
main.\n";
Deep();
// Call function Deep
cout << "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..
Back in function main again.
Checkpoint
6.1 Is the following a function or a function
call?
calcTotal();
6.2 Is the following a function header or a
function call?
void showResults();
Function Prototypes
• The function prototype is a statement used
to communicate to the compiler a functions:
– return type
– the number of parameters
– the parameters data type
• Looks similar to the function header except
the parameter variables are left out.
Return_type function_name (data_type, data_type,..)
Concept - A function prototype eliminates the need to place a
function definition before all calls to the function
/* Definition of function First. This
function displays a message.*/
void First(void)
{
// This program has three functions: main,
cout << "I am now inside the
First, and Second.
function First.\n";
#include <iostream.h>
}
//Function Prototypes
/* Definition of function Second. This
void first (void);
function displays a message.*/
void second (void);
void Second(void)
void main(void)
{
{
cout << "I am now inside the
cout << "I am starting in function
function Second.\n";
main.\n";
}
First();
// Call function First
Second();
// Call function Second Program Output
I am starting in function main.
cout << "Back in function main
I am now inside the function First.
again.\n";
I am now inside the function Secon
}
Program 6-5
Back in function main again.
Sending Information to a Function
• Values sent into a function are called
arguments.
• Arguments initialize the parameters (formal
arguments) of a function.
• Arguments are promoted or demoted
automatically to match the data type of the
corresponding parameter.
Concept - When a function is called, the program may send
values into the function
Program 6-6
/* This program demonstrates a
function with a parameter*/
#include <iostream.h>
void main(void)
{
cout << "I am passing 5 to
DisplayValue.\n";
/* Call DisplayValue with
argument 5 */
DisplayValue(5);
cout << "Now I am back in
main.\n";
}
/* Definition of function
DisplayValue. It uses an
integer parameter whose
value is displayed. */
void DisplayValue(int Num)
{
cout << "The value is " <<
Num << endl;
}
Program Output
I am passing 5 to
DisplayValue
The value is 5
Now I am back in main.
/* Definition of function
DisplayValue. It uses an
Program 6-7
integer parameter whose
value is displayed.*/
void DisplayValue(int Num)
/* This program demonstrates a
function with a parameter.*/
{
#include <iostream.h>
cout << "The value is " <<
//fuction Prototype
Num << endl;
void DisplayValue(int);
}
void main(void)
Program Output
{
I am passing several
cout << "I am passing several
values to
values to DisplayValue.\n";
DisplayValue.
DisplayValue.\n";
The value is 5
DisplayValue(5);
DisplayValue(10);
The value is 10
DisplayValue(2);
The value is 2
DisplayValue(16);
The value is 16
cout << "Now I am back in main.\n";
Now I am back in main
}
// This program demonstrates a
function with three parameters.
#include <iostream.h>
//Function Prototype
void ShowSum (int, int, int);
void main(void)
{
int Value1, Value2, Value3;
cout << "Enter three integers and I
will display ";
cout << "their sum: ";
cin >> Value1 >> Value2 >> Value3;
// Call ShowSum with 3 arguments
ShowSum(Value1, Value2, Value3);
}
Program 6-8
/* 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;
}
Program Output
Enter three integers and I will
display their sum: 4 8 7
[Enter]
19
Changing the value of a parameter
• Parameters are special-purpose variables
– declared inside the parentheses of a function
– initialized by the arguments from the statement
that called the function.
• When only a copy of an argument is passed
to a function it is said to be passed by value
Concept - When an argument is passed into a parameter, it is
only a copy of the argument's value that is passed
/* This program demonstrates that
changes to a function parameter have
no effect on the original argument. */
/* Definition of function ChangeThem.
#include <iostream.h>
It uses I, an int parameter, and F, a
float. */
//Function Prototype
void ChangeThem(int I, float F)
void ChangeThem(int , float )
{
void main(void)
I = 100;
{
F = 27.5;
int Whole = 12;
cout << "In ChangeThem the value
float Real = 3.5;
is changed to ";
cout << "In main the value of Whole of I
cout << I << endl;
is " << Whole << endl;
cout << "and the value of F is
cout << "and the value of Real is "
changed
to " << F << endl;
<<
Real << endl;
}
ChangeThem(Whole, Real);
Program Output
cout << "Now back in main again,
In main the value of Whole is 12 and the
the
value of ";
value of Real is 3.5
cout << "Whole is " << Whole << In ChangeThem the value of I is changed to
endl;
100 and the value of F is changed to 27.5
cout << "and the value of Real is " Now back in main again, the value of Whole
<<
Real << endl;
is 12 and the value of Real is 3.5
Program 6-9
//Function Prototypes
void Adult(int);
void Child(int);
void Senior(int);
void main(void)
{
do
{
cout << "Health Club Membership Menu";
cout << "1. Standard Adult Membership";
cout << "2. Child Membership";
cout << "3. Senior Citizen Membership";
cout << "4. Quit the Program";
cout << "Enter Your Choice
cin >> choice;
if (choice >0 && choice <4)
{
cout <<"For How Many Months";
cin >> months;
}
Using Functions in a
Menu Driven Program
Switch (choice)
{
case 1 : Adult (months);
break;
case 2 : Child (months);
break;
case 3 : Senior (months);
break;
case 4 : exit(0);
break;
default: cout <<"Enter a number";
cout <<" between 1 - 4";
}
while (choice <0 || choice >4)
}
Concept - Functions are ideal for use in menu-driven programs
Checkpoint
6.5 Indicate which of the following is the function prototype,
the function header, and the function call:
void showNum(float num)
Function header
Function prototype
void showNum(float);
Function call
showNum(45,67);
6.6 Write a function named ‘timesTen’.
function number)
should
void The
timesTen(int
have an integer parameter named{ ‘number’. When
‘timesTen’ is called, it should display thecout
product
of
<< number
* 10;
‘number’ times ten. (note: just write
} the function. Do no
write a complete program.)
6.7 Write a function prototype for the ‘timesTen’ function
written in 6.6.
void timesTen(int);
The return Statement
• When the last line of a function is executed,
program control is returned to the statement
following the function call.
• The return statement is used to terminate the
execution of a function before all the
statements have been executed.
return;
Concept - The return statement cause the function to end.
‘Return’ Example
/* This program demonstrates a
function with a return
statement.*/
#include <iostream.h>
// Function prototype
void Halfway(void);
void main(void)
{
cout << "In main, calling
Halfway...\n";
Halfway();
cout << "Now back in
main.\n";
}
/* Definition of function Halfway.
This function has a return
statement that forces it to
terminate before the last
statement is executed.*/
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.
Program 6-11
/* Definition of function Divide. Uses
two parameters: Arg1 and Arg2.
The function divides Arg1 by Arg2
and shows the result. If Arg2 is
zero, however, the function
returns.*/
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;
}
/* 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)
{
float Num1, Num2;
cout << "Enter two numbers and I
will divide the first\n";
cout << "number by the second
number: ";
cin >> Num1 >> Num2;
Program Output
Divide(Num1, Num2);
Enter two numbers and I will divide the first
}
number by the second number: 12 0 [Enter]
Sorry, I cannot divide by zero
Returning a value from a Function
• If a function returns a value it can be used
as an expression.
• Any function returning a value must contain
a return statement.
• Example: int square(int); int square (int num)
void main(void)
{
A = square(7);
}
{
return num * num;
}
Concept - A function may send a value back to the part of the
program that called the function.
Program 6-12
/* This program uses a function
that returns a value.*/
#include <iostream.h>
//Function prototype
int Square(int);
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;
}
/* Definition of function
Square.This function accepts
an int argument and returns
the square of the argument
as an int.*/
int Square(int Number)
{
return Number * Number;
}
Program Output
Enter a number and I will
square it: 20 [Enter]
20 squared is 400
Returning Boolean Values
• In C++ a value of 0 represents false and all
other values are considered true.
• Any C++ statement can use a function call
as its relational expression if a 0 or non 0
value is returned by the function.
Concept - Functions may return true or false values.
/* Definition of function IsEven. This
function accepts an integer
argument and tests it to be even or
odd. The function returns true if the
/* This program uses a function that
argument is even or false if the
returns true or false.
argument is odd. The return value
#include <iostream.h>
is bool. */
// Function prototype
bool IsEven(int Number)
bool IsEven(int);
{
void main(void)
if (Number % 2)
{
/* The number is odd if there's a
int Val;
remainder.*/
cout << "Enter an integer and I will tell
return false;
you ";
else
cout << "if it is even or odd: ";
// Otherwise, the number is even.
cin >> Val;
if (IsEven(Val))
return true;
cout << Val << " is even.\n";
}
else
Enter an integer and I will tell you if it is
cout << Val << " is odd.\n"; even or odd: 5 [Enter]
}
5 is odd.
Program 6-14
Local Variables
• Very similar to block scope
• Variables declared inside a function may
have names identical to variables declared
outside the function.
Concept - A local variable is declared inside a function, and is
not accessible outside the function.
Program 6-15
/* This program shows that
variables declared in a
function are hidden from
other functions.*/
#include <iostream.h>
void Func(void); // Function
prototype
void main(void)
{
int Num = 1;
cout << "In main, Num is " <<
Num << endl;
Func();
cout << "Back in main, Num
is still " << Num << endl;
}
/* Definition of function Func. It
has a local variable, Num,
whose initial value, 20, is
displayed.*/
void Func(void)
{
int Num = 20;
cout << "In Func, Num is "
<< Num << endl;
}
Program Output
In main, Num is 1
In Func, Num is 20
Back in main, Num is still 1
Global Variables
• Variables that must be accessible to all
functions are called a global variables.
• Unless initialized in the declaration, global
variables are automatically set to zero.
Concept - Global variables are declared outside all functions
and are accessible to any function within their scope.
Program 6-16
/* 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>
// Function prototype
void Func(void);
int Num = 2;
// Global
variable
void main(void)
{
cout << "In main, Num is "
<< Num << endl;
Func();
cout << "Back in main, Num is
/* Definition of function Func.
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 2
In Func, Num is 2
But, it is now changed to 50
Back in main, Num is 50
Program 6-16
/* 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>
// Function prototype
void Func(void);
void main(void)
{
cout << "In main, Num is not visible
" << endl;
Func();
cout << "Back in main, Num
is still not visible" << endl;
}
int Num = 2; // Global variable
/* Definition of function Func. 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 vissible
In Func, Num is 2
But, it is now changed to 50
Back in main, Num is still not visible
Program 6-17
/* This program has an
uninitialized global variable.*/
#include <iostream.h>
/* Global variable. Automatically
set to zero.*/
int GlobalNum;
void main(void)
{
int LocalNum
cout << "GlobalNum is "
<< GlobalNum << endl;
cout << " LocalNum is "
<< LocalNum << endl;
}
Program Output
GlobalNum is 0
LocalNum is ??????
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
Concept - A local variable may have the same name as a global
variable
Program 6-18
/* This program shows that when a
local variable has the same name
as a global variable, the function
only sees the local variable.*/
#include <iostream.h>
// Function prototypes
void Texas(void);
void Arkansas(void);
int Cows = 10;
void main(void)
{
cout << "There are " << Cows << "
cows in main.\n";
Texas();
Arkansas();
cout << "Back in main, there are "
<< Cows << " cows.\n";
}
// The local variable Cows is set to
100.
void Texas(void)
{
int Cows = 100;
cout << "There are " << Cows << "
cows in Texas.\n";
}
// The local variable Cows is set to 50.
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.
do
{
Program 6-19
/* 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>
// Function prototype
void RingUpSale(void);
// Global Variables
const float TaxRate = 0.06;
float Sale;
void main(void)
{
float Tax, Total;
char Again;
cout.precision(2);
cout.setf(ios::fixed |
ios::showpoint);
RingUpSale();
cout << "Is there another item
to be purchased? ";
cin >> Again;
} while (Again == 'y' || Again == 'Y');
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 price of an item. It then
calculates and displays the sales
tax and subtotal for those items. */
void RingUpSale(void)
{
int Qty;
float UnitPrice, Tax, ThisSale,
SubTotal;
cout << "Quantity: ";
cin >> Qty;
cout << "Unit price: ";
cin >> UnitPrice;
// Get the total unit price
ThisSale = Qty * UnitPrice;
// Update global variable Sale
Sale += ThisSale;
Tax = ThisSale * TaxRate; // Get
sales tax for these items
SubTotal = ThisSale + Tax; // Get
subtotal for these items
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 Input
Quantity: 2 [Enter]
Unit Price: 20.00 [Enter]
Price for these items: 40.00
Tax for these items: 2.40
SubTotal for these items: 42.40
Is there another item to be purchased? y [Enter]
Quantity: 3 [Enter]
Unit Price: 12.00 [Enter]
Price for these items: 36.00
Tax for these items: 2.16
SubTotal for these items: 38.16
Is there another item to be purchased? n [Enter]
The tax for this sale is 4.56
The total is 80.56
Be Careful with Global Variables
• Makes debugging difficult
– Trying to find where a global variable was
modified.
– One function can change the correctness or
accuracy of a variable used by another.
• Particularly critical if more than one person
is working on the same program
• Requires a very disciplined approach
Concept - Overuse of global variables can lead to problems as
programs become larger and more complex