1 functions - i chapter 5. 2 what are functions ? large programs can be modularized into sub...

44
1 FUNCTIONS - I Chapter 5

Upload: tabitha-allen

Post on 17-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

1

FUNCTIONS - IChapter 5

Page 2: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

2

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

Page 3: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

3

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

Page 4: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

4

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

Page 5: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

5

Example :The sqrt() function…This function returns the square root of a given positive number

// sqroot.cpp#include <iostream>#include <cmath>using namespace std;

int main(){ int x; x = 2; cout << sqrt(9) << endl; cout << sqrt (10*x + 5) << endl; cout << sqrt(x) << endl; return 0;}

Calls sqrt()

Method 1, function call in a cout statement

3

5

1.41421

New library

Page 6: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

6

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;

Method 2, function call in an assignment statement

25 5

Page 7: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

7

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)

Page 8: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

8

This can be illustrated as :

3

1.73205

float x

float y

3

1.73205

main()sqrt()

Shaded box,

Processing hidden

Page 9: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

9

Check this out…!!

Nesting of function calls…

int main()

{

float y;

y = sqrt(1 + 2*sqrt(3 + 4*sqrt(5)));

cout<< y<< endl;

}

Page 10: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

10abs(k) works with integers

Page 11: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

11

Page 12: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

12

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’

Page 13: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

13

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;

}

Page 14: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

14

Random Number functions// random.cpp#include <iostream>#include <ctime>using namespace std;

int main(){

srand(time(NULL));cout << rand()<< endl; //new random 0 - 2billioncout << rand()<< endl; //new random 0 - 2billion cout << rand()%10<< endl; // 0 - 9cout << rand()%6 + 1<< endl; // 1 – 6 dice rollcout << rand()%6 + 1<< endl; // 1 – 6 dice roll

return 0;}

Has time function

Seed random nums gen

Page 15: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

15

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

Page 16: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

16

User-defined functionsA user defined function has two parts :the head and the body

Here is a simple example of a user definedfunction:

float cube(float x){ return x*x*x; //returns cube of x}

Page 17: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

17

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

Page 18: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

18

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 headerIt contains the code that performs the function’s actionNote that main() is a function whose body is the program itself

Page 19: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

19

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

Page 20: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

20

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

Page 21: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

21

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

Page 22: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

22

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…

Page 23: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

23

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

Page 24: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

24

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

Page 25: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

25

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;

}

Page 26: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

26

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

Page 27: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

27

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;

}

Page 28: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

28

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

Page 29: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

29

Actual Vs. Formal Parameters

float cube(float); // function declarationint main() { float n=1; while (n > 0) { cin>> n; cout<<"cube("<< n <<") = "<< cube(n) <<endl; } } // function definitionfloat cube(float x) { // returns cube of x: return x*x*x; }

Actual Parameter n

Formal parameter x

The value of n is copied into x for each function call

Page 30: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

30

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

Page 31: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

31

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

Page 32: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

32

int max (int a, int b){ int larger; if (a > b) larger = a; else larger = b; return larger;}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;}

The variable larger is

local to max…only can be

used inside max

Parameters a & b are

like local variables too…only

work inside max

Page 33: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

33

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 listThe parameter larger is local because it is declared within the body of the function

Page 34: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

34

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

Page 35: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

35

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; } }

Page 36: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

36

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; }

Page 37: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

37

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

Page 38: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

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():

float x = grade(95);

cout<<“grade(95)= "<< x ;

}

What’s wrong here?

Page 39: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

39

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

Page 40: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

40

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

Page 41: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

41

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

Page 42: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

42

This function does not return anything:

void printhello(float x) { for (int i=0; i<x; i++) { cout<< "Hi There !!!!" << endl; }

}

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)

No return statement

Page 43: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

43

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

Page 44: 1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and

44

Summarizing what we did today..

Standard C++ library functions

User - defined functions

Test Drivers

Function Declarations and Definitions

Local variables and Functions

void functions