CSCI 110 STRUCTURED PROGRAMMING WITH C++

advertisement
CSCE 110
PROGRAMMING FUNDAMENTALS
WITH
C++
Prof. Amr Goneid
AUC
Part 5. Functions
Prof. amr Goneid, AUC
1
Functions
Prof. amr Goneid, AUC
2
Functions








Predefined (Library) Functions
Modular Programming with Functions
Types of Functions
Function Prototype Declaration
Function Definition
Formal & Actual Parameters
Who Sees Who: Scope of an Identifier
Parameter Passing
Prof. amr Goneid, AUC
3
1. Predefined Functions
Example:
#include <math.h>
void main()
{
cout << ”Square Root. Ex: sqrt(9.0) = ”
<< sqrt(9.0) << endl;
cout << ”Powers. Ex: pow(3.0, 4.0) = ”
<< pow(3.0,4.0) << endl;
cout << ”Absolute Value for int. Ex: ”
<< ”abs(-9) = ” << abs(-9)
<< endl;
cout << ”Absolute Value for long. Ex: ”
<< ”labs(-900) = ” << labs(-900)
<< endl;
Prof. amr Goneid, AUC
4
cout <<
<<
<<
cout <<
<<
cout <<
<<
<<
”Absolute Value for double. Ex: ”
”fabs(-9.5) = ” << fabs(-9.5)
”\n”;
”Ceiling (round up). Ex: ceil(4.1)”
” = ” << ceil(4.1) << endl;
”Floor (round down). ”
”Ex: floor(4.7) = ”
floor(4.7) << endl;
}
Output:
Square Root. Ex: sqrt(9.0) = 3.0
Powers. Ex: pow(3.0,4.0) = 81
Absolute Value for int. Ex: abs(-9) = 9
Absolute Value for long. Ex: labs(-9000) = 9000
Absolute Value for double. Ex: fabs(-9.5) = 9.5
Ceiling (round up). Ex: ceil(4.1) = 5
Floor (round down). Ex: floor(4.7) = 4
Prof. amr Goneid, AUC
5
2. Modular Programming with
Functions
Level
0
1
Main Function
Function1
Function2
Function3
2
Function4
Function5
.
.Functions are natural building blocks for modular programming
Prof. amr Goneid, AUC
6
C++ Program Structure
Compiler Directives
Function Prototypes
int main ( )
{
Main Data Declarations
Main Actions
}
C++ program
contains
function
prototype
declarations
and function
definitions.
The main is
just another
function.
Used Functions Defined Here
Prof. amr Goneid, AUC
7
Functions & The Main Function
A function is invoked by another function (e.g main)
int main( )
Function Header
main
Data Area
Local
Data Area
Main Body
Function Body
Invoke function
Next action
Prof. amr Goneid, AUC
8
3. Types of Functions
Returns a Single
Scalar Value
Input Params
Typed
Function
Output Params
Input Params
void
Function
Action
Prof. amr Goneid, AUC
9
4. Function Prototype
Declaration
 Syntax:
<ftype> <fname> (formal parameter list) ;
 Examples:
int cube ( int n ) ;
// A function receiving an int parameter (n) and returning
an int value.
float minxy ( float x , float y ) ;
// A function receiving two float parameters ( x , y ) and
returning a float value.
Prof. amr Goneid, AUC
10
Prototype Declaration (Examples)
 void printchar ( char c , int n ) ;
// a function receiving two parameters ( c , n ) and
returns nothing. It is supposed to do an action, e.g.
print n of char c on one line.
 void errormessage ( ) ;
// a function receiving nothing and returning nothing.
It is supposed to do an action, e.g. print a fixed error
message.
Prof. amr Goneid, AUC
11
5. Function Definition
<ftype> <fname> ( List of Formal Parameters)
{
Local Data Declarations
Function Actions
(Executable Statements)
}
Prof. amr Goneid, AUC
12
Building Typed Functions
 Syntax:
<ftype> <fname> (formal params)
{
Local Data Area
Function Body contains a statement:
return < a value of type ftype > ;
}
Prof. amr Goneid, AUC
13
Example of an Integer
Function
 Function to return the larger of two integer
numbers a and b.
int maxab ( int a , int b )
{
//Does not need Local Data
return ( (a >= b) ? a : b );
}
Prof. amr Goneid, AUC
14
Example of a Real Function
 Function to return the area of a circle of radius r.
float area ( float r )
{
// Local Data
const float pi = 3.14159 ;
// Action
return ( pi * r * r ) ;
}
Prof. amr Goneid, AUC
15
Example of a Boolean Function
 Function to return true if an integer n is even and
false otherwise.
bool iseven ( int n )
{
//Does not need Local Data
return ( n % 2 == 0 ) ;
}
Prof. amr Goneid, AUC
16
Example of Using a Typed
Function
// Prints if an entered integer is even or odd
# include <iostream>
using namespace std;
// Function used….
bool iseven ( int n );
int main ( )
{
int num;
cout << “ Enter an integer number: “;
cin >> num;
Prof. amr Goneid, AUC
17
Example of Using a Typed
Function
if ( iseven ( num ) ) cout << “ Number is even ! “ ;
else cout << “ Number is odd ! “;
return 0 ;
}
// Returns true if an integer is even, false otherwise
bool iseven ( int n )
{
return ( n % 2 == 0 );
}
Prof. amr Goneid, AUC
18
Type of Returned Value
 Type of a value returned by a called
function must be consistent with the
type expected by the caller as identified
in the function prototype declaration.
Prof. amr Goneid, AUC
19
Building void Functions
 Syntax:
void <fname> (formal params)
{
Local Data Area
Function Body does not contain a
return statement
}
Prof. amr Goneid, AUC
20
Example of a void Function
 Action: Fill screen with blanks.
void blankscreen( )
{
const char blank = ‘ ’ ;
int row , col ;
for (row = 1; row <= 25; row++) {
for (col = 1; col <= 80; col++)
cout << blank ;
cout << endl;
}
}
Prof. amr Goneid, AUC
21
Example of a void Function
 Action: Write n dashes on a line.
void dashes( int n )
{
const char dash = ‘-’ ;
int i ;
for (i = 1; i <= n; i++)
cout << dash ;
}
Prof. amr Goneid, AUC
22
Example of Using a void
Function
// Prints numbers and dashes
# include <iostream>
using namespace std;
// Function used….
void dashes ( int n );
int main ( )
{
float salary, bonus;
cout << “Enter Salary: “; cin >> salary;
bonus = 0.1 * salary ;
Prof. amr Goneid, AUC
23
Example of Using a void
Function
cout << “Bonus ” ; dashes(3);
cout << bonus; dashes(5); cout << endl;
return 0 ;
}
// Writes n dashes on one line
void dashes ( int n )
{
const char dash = ‘-’ ;
int i ;
for (i = 1; i <= n; i++) cout << dash ;
}
Prof. amr Goneid, AUC
24
6. Formal & Actual Parameters
In Function Declarations:
bool iseven(int n); int maxab( int a , int b )
void dashes(int n);
a,b,n are FORMAL parameters(Dummies or Gates).
They are LOCAL to their modules.
When invoked in a main function:
maxab(x,y) or maxab(1+z,2.3) dashes(7);
dashes(k); iseven ( num )
x , y , 1+z , 2.3 , 7 , k , num are ACTUAL parameters
passed from main to modules through their
respective gates.
Prof. amr Goneid, AUC
25
Key Points
The substitution of the value of an
actual parameter in a function call for its
corresponding formal parameter is
strictly positional. That is, the value of
the first actual parameter is substituted
for the first formal parameter; the
second and so on
Prof. amr Goneid, AUC
26
Key Points
 The names of these corresponding pairs of
parameters are no consequence in the
substitution process. The names may be
different, or they may be the same.
 The substituted value is used in place of the
formal parameter at each point where that
parameter appears in the called function.
Prof. amr Goneid, AUC
27
Passing values of Actual
Parameters
main
maxab
x
a
y
b
main
num
Prof. amr Goneid, AUC
iseven
n
28
Formal & Actual Parameters
 Correspondence between actual and formal
parameters is determined by position in their
respective lists. These lists must be the same
size. The names of corresponding actual and
formal parameters may be different.
 Formal parameters and corresponding actual
parameters should agree with respect to type.
Prof. amr Goneid, AUC
29
Overloaded Functions:
#include <iostream.h>
float average(float x, float y);
// Returns the average of x and y
float average(float x, float y, float z);
// Returns the average of x, y, and z
void main()
{
cout << ”The average of 3.0 and 7.0”
<< ” is ” << average(3.0, 7.0)
<< endl;
cout << ”The average of 3.0, 4.0, and 8.0”
<< ” is ” << average(3.0, 4.0,8.0)
<< endl;
}
Prof. amr Goneid, AUC
30
float average(float x, float y)
{
return ((x + y)/2.0);
}
float average(float x, float y, float z)
{
return ((x + y + z)/3.0);
}
Output:
The average of 3.0 and 7.0 is 5.0000
The average of 3.0, 4.0, and 8.0 is 5.0000
Prof. amr Goneid, AUC
31
7. Who Sees Who:
Scope of an Identifier
 To see = to recognize = to be able to use,
invoke, change, etc.
 Scope = the domain in which an identifier is
recognizable.
 The scope of an identifier extends only from
the point where it is defined to the end of the
module in which it is defined.
 A module can see itself (Recursion)
Prof. amr Goneid, AUC
32
Scope(continued)
 Global : can be seen by all modules.
 Local: can be seen only by its module but not by




other modules.
Names declared inside a function/main are local to
that function/main.
Anything declared before the main function is global.
It can be called anywhere in the program.
Hence, all functions are global.
For two things having the same id, local overrides
global.
Prof. amr Goneid, AUC
33
Scope(example)
int x , m; // Global Variables
Prototypes of A , B , C
Main
Data x , y
Module A
Data P , Q
Module B
Module C
Data x , w
Data m , n
Prof. amr Goneid, AUC
34
8. Parameter Passing:
Example of a Paradox
 A function to swap two characters.
// x and y are passed by value
void swap (char x , char y)
{
char temp;
temp = x;
x = y;
y = temp;
}
Prof. amr Goneid, AUC
35
Paradox (continued)
 A program uses the function to swap two characters:
void swap (char x , char y);
int main ( )
{
char a,b ;
a = ‘M’ ; b = ‘N’ ;
cout << a << ‘ ‘ << b << endl;
swap(a,b);
cout << a << ‘ ‘ << b << endl;
}
Prof. amr Goneid, AUC
No Change!
Why ?
MN
MN
36
Where in Memory?
 The DOS Memory Map:
one segment = 64 kbyte
DOS
CS
DS
SS
HEAP
LM
DS = Data Segment (Data)
CS = Code Segment ( Main & Modules code)
SS = Stack Segment (System Stack)
Heap = Rest of DOS memory
Prof. amr Goneid, AUC
HM
37
Parameter Passing:
What Really Happened
Memory Before
DS
b ‘N’
a ‘M’
Memory After
SS
DS
‘N’-> y
‘M’ -> x
b
a
Swap addr
Prof. amr Goneid, AUC
‘N’
‘M’
SS
‘M’ <- y
‘N’ <- x
Swap addr
38
To see the change, pass the
address, not the value !
Memory Before
Memory After
DS
SS
DS
b ‘N’
a ‘M’
Addr of b
Addr of a
b
a
Swap addr
Prof. amr Goneid, AUC
‘M’
‘N’
SS
Addr of b
Addr of a
Swap addr
39
How to pass the Address (pass
by Reference)
 The correct function to swap two characters.
// x and y are passed by reference
void swap (char& x , char& y)
{
char temp;
temp = x;
x = y;
y = temp;
}
// symbol & means address of
Prof. amr Goneid, AUC
40
Passing by Reference
(continued)
 A program uses the function to swap two characters:
void swap (char& x , char& y);
int main ( )
{
char a,b ;
a = ‘M’ ; b = ‘N’ ;
cout << a << ‘ ‘ << b << endl;
swap(a,b);
cout << a << ‘ ‘ << b << endl;
}
Prof. amr Goneid, AUC
Now there is
Change!
MN
NM
41
Parameter Passing:
Summary
 Input Only Parameters: those you do
not want to change- pass by value
 Output Only Parameters: those you
want to see what happened to them –
pass by reference (address) using &.
 Input/Output Parameters: pass by
reference using &.
Prof. amr Goneid, AUC
42
Download