Lect5.ppt

advertisement
FUNCTIONS - I
Chapter 5
1
What are functions ?
Large programs can be modularized into sub
programs which are smaller, accomplish a
specific task and hence are more
manageable
These sub programs are called functions
They can be compiled and tested separately
and reused in different programs
2
Things to do today…
Functions Basics including…
Standard C++ library functions
User - defined functions
Test Drivers
Function Declarations and Definitions
Local variables and Functions
void Functions
3
Standard C++ Library
As we have already seen, the Standard C++
library is a collection of pre-defined functions
which are accessed through header files
Notice about these pre-defined functions that
the processing step is hidden : we do not
need to know what the function does to
produce the output
4
Example :The sqrt() function…
This function returns the square root of a given positive
number
New library
// sqroot.cpp
#include <iostream>
#include <cmath>
3
using namespace std;
5
int main()
1.41421
{
Calls sqrt()
int x;
x = 2;
cout << sqrt(9) << endl;
cout << sqrt (10*x + 5) << endl;
cout << sqrt(x) << endl;
return 0;
}
Method 1, function call in a cout statement
5
Invoking a function, method 2
A function can be invoked or called in a cout
statement as shown in the previous example
or by assigning its value to a variable
Example :
float x=25, y;
y=sqrt(x);
cout<< x <<“
"<< y << endl;
25
Method 2, function call in an assignment statement
6
5
Passing by value… What’s that ?
Consider the function sqrt(x):
The expression x is called the argument or
actual parameter of the function call and we
say that it is passed by value to the function
So when x is 3, the actual value 3 is passed
to the sqrt() function by the call sqrt(x)
7
This can be illustrated as :
main()
sqrt()
float x
float y
3
3
1.73205
1.73205
Shaded box,
Processing hidden
8
Check this out…!!
Nesting of function calls…
int main()
{
float y;
y = sqrt(1 + 2*sqrt(3 + 4*sqrt(5)));
cout<< y<< endl;
}
9
abs(k) works with integers
10
11
Functions for processing char data
(already included in namespace std)
Function
Description
Example
isalnum(c)
isalpha(c)
isdigit(c)
islower(c)
isprint(c)
ispunct(c)
isupper(c)
tolower(c)
toupper(c)
Tests if a char is alphanumeric
Tests if a char is a letter
Tests if a char is digit
Tests for lowercase letter
Tests for printable letter
Tests for punctuation
Tests for uppercase letter
Takes upper case gives lower
Takes lower case gives upper
isalnum(‘x’) gives T
isalpha(‘$’) gives F
isdigit(‘3’) gives T
islower(‘A’) gives F
isprint(‘\n‘) gives F
ispunct(‘!’) gives T
isupper(‘A’) gives T
tolower(‘G’) gives ‘g’
toupper(‘g’) gives ‘G’
12
Example use of char functions
char ch;
cin>>ch;
if (islower(ch))
{
cout << ch <<“ is lowercase letter” << endl;
ch = toupper(ch);
cout<<“Uppercase version is” <<ch<<endl;
}
13
Random Number functions
// random.cpp
#include <iostream>
#include <ctime>
using namespace std;
Has time function
Seed random
nums gen
int main()
{
srand(time(NULL));
cout << rand()<< endl; //new
cout << rand()<< endl; //new
cout << rand()%10<< endl; //
cout << rand()%6 + 1<< endl;
cout << rand()%6 + 1<< endl;
return 0;
}
random
random
0 - 9
// 1 –
// 1 –
0 - 2billion
0 - 2billion
6
6
dice roll
dice roll
14
Things to do today…
Functions Basics including…
Standard C++ library functions
User - defined functions
Test Drivers
Function Declarations and Definitions
Local variables and Functions
void Functions
15
User-defined functions
A user defined function has two parts :
the head and the body
Here is a simple example of a user defined
function:
float cube(float x)
{
return x*x*x; //returns cube of x
}
16
User-defined functions.. Contd..
The syntax for the head of a function is :
return-type name(parameter-list)
In the given example the head of the function is:
float cube(float x)
return-type name(parameter-list)
Another example:
double dollar_value (int d, int q)
// return value of dimes and quarters
17
The function body
The body of a function is the block of
code that follows its head
It is written between the { } braces
following the function header
It contains the code that performs the
function’s action
Note that main() is a function whose
body is the program itself
18
In the example…
The function body is :
{
return x*x*x; //returns cube of x
}
This includes the return statement that
specifies the value that the function sends
back to the place where it was called
19
return…
It terminates the execution of the function
The function’s return-type specifies the
data type of the values that it would return to
the calling program
Its syntax is :
return expression ;
where the data-type of the expression
value = function's return-type
20
Things to do today…
Functions Basics including…
Standard C++ library functions
User - defined functions
Test Drivers
Function Declarations and Definitions
Local variables and Functions
void Functions
21
Does my function work right ?
That is the purpose of the test driver
It is an ad-hoc program(minus all the usual
niceties such as user prompts, output labels
and documentation) written to test a function
that we have created
Remember the cube() function ? Let’s write
a test driver for that…
22
float cube(float x)
{ // returns cube of x:
return x*x*x;
}
int main()
{ // test driver for cube() function:
cout<<"cube(1)= "<<cube(1)<<endl;
cout<<"cube(-5)= "<<cube(-5)<<endl;
cout<<"cube(4)= "<<cube(4)<<endl;
1
-125
64
}
23
Things to do today…
Functions Basics including…
Standard C++ library functions
User - defined functions
Test Drivers
Function Declarations and Definitions
Local variables and Functions
void Functions
24
Two ways for defining functions
The complete definition of the function is
listed above the main program like :
float cube(float x)
{ // returns cube of x:
return x*x*x;
}
int main()
{
float n=5;
cout<< cube(n) << endl;
}
25
Another way is…
List only the function’s header above the main
program (declaration) like :
float cube(float);
(or)
float cube(float x);
List the function’s head and body below the
main program (definition)
declaration is also called a function prototype
A function declaration is like a variable
declaration
26
The previous program can also be
written as :
float cube(float x); //declaration
int main()
{
float n=5;
cout<< cube(n) << endl;
}
float cube(float x) //definition
{ // returns cube of x:
return x*x*x;
}
27
Actual Vs. Formal Parameters
Actual parameters (We use ARGUMENTS)
Parameters of the function in the function call
Passed by value
Formal parameters
Variables listed in the function’s parameter-list in the
function definition
Local to that function
The Arguments are copied to the Formal
Parameters during function call
28
Actual Vs. Formal Parameters
float cube(float); // function declaration
int main()
{
float n=1;
Actual Parameter n
while (n > 0)
{ cin>> n;
cout<<"cube("<< n <<") = "<< cube(n) <<endl;
}
}
// function definition
Formal parameter x
float cube(float x)
{ // returns cube of x:
return x*x*x;
}
The value of n is copied into x for each function call
29
Things to do today…
Functions Basics including…
Standard C++ library functions
User - defined functions
Test Drivers
Function Declarations and Definitions
Local variables and Functions
void Functions
30
Local variables and functions
A local variable is declared inside a block and
is accessible only from within that block
Similarly a variable declared within a function
is local to that function.. i.e it exists only when
the function is executing
A function’s formal parameters (used at that
point where the function is actually defined)
are also regarded as being local to the
function
31
The variable larger is
local to max…only can be
used inside max
int max (int a, int b)
{
int larger;
if (a > b)
larger = a;
else
Parameters a & b are
larger = b;
like local variables too…only
return larger;
work inside max
}
int main()//tests the max() function:
{ cout<<“max(5, 8) =”<<max(5,8)<<endl;
cout<<“max(7, 3) =”<<max(7,3)<<endl;
cout<<“max(7, 7) =”<<max(7,7)<<endl;
}
32
In the last example
The function has three local variables :
a,b and larger
The parameters a & b are local
because it is declared in the function’s
formal parameter list
The parameter larger is local because
it is declared within the body of the
function
33
The max function could also be
written without a local variable
int max(int a, int b)
{
int larger;
if (a > b)
larger = a;
else
larger = b;
return larger;
}
int max(int a, int b)
{
if (a > b)
return a;
else
return b;
}
Both work the same way
34
What’s wrong with this ?
float cube(float x)
{ // returns cube of x:
return x*x*x;
}
int main() // tests the cube() function:
{float n;
cin>>n;
while (n > 0)
{
x = cube(n);
cout<<"cube(“ << n << ") = “ <<x<<endl;
cin >> n;
}
}
35
What’s wrong with this ?
float cube(float x)
{ // returns cube of x:
return x*x*x;
}
int main()
{ // test driver for cube() function:
x = cube(1);
cout<<"cube(1)= "<< x <<endl;
cout<<"cube(-5)= "<<cube(-5)<<endl;
cout<<"cube(4)= "<<cube(4)<<endl;
}
36
This would work !
float cube(float x)
{ // returns cube of x:
return x*x*x;
}
int main()
{ // test driver for cube() function:
float x = cube(1);
cout<<"cube(1)= "<< x <<endl;
cout<<"cube(-5)= "<<cube(-5)<<endl;
cout<<"cube(4)= "<<cube(4)<<endl;
}
But for now, try not to reuse variable names in functions
37
Data Types Must Match!
char grade (double avg)
{
if (avg >= 92)
return 'H';
else if (avg >= 65)
return 'P'
else
return 'F';
}
int main()
{ // test driver for grade():
float x = grade(95);
cout<<“grade(95)= "<< x ;
}
What’s wrong here?
38
Data Types Must Match!
char grade (double avg)
{
if (avg >= 92)
return 'H';
else if (avg >= 65)
return 'P'
else
return 'F';
}
int main()
{ // test driver for grade():
char G = grade(95);
cout<<“grade(95)= "<< G ;
}
Hint for Problem 10
39
Things to do today…
Functions Basics including…
Standard C++ library functions
User - defined functions
Test Drivers
Function Declarations and Definitions
Local variables and Functions
void Functions
40
void Functions
If a function does not return any value
its return-type is void
The void type specifies the empty set
Think of an example for this type of
function that does not return anything
41
This function does not return anything:
void printhello(float x)
{
for (int i=0; i<x; i++)
{
cout<< "Hi There !!!!" << endl;
}
}
No return statement
int main()
{
printhello(2);
}
Also Notice a void function call
is just on a line by itself
Don’t use in cout or
assignment statements
(like float functions)
42
And now for….
Global Variables-A variable declared above/outside all functions
Can be accessed by everyone
Generally not a good idea for beginners
Global Constants—
A variable declared above/outside all functions
Can be accessed by everyone
Works great for things like PI that you use
often
43
Summarizing what we did today..
Standard C++ library functions
User - defined functions
Test Drivers
Function Declarations and Definitions
Local variables and Functions
void functions
44
Download