chapter 4 functions and methods :

44
Chapter 4 Functions and methods: General syntax: return_type function_name(par 1 , par 2 , …,par n ) Each should contain comments. If it’s associated with a class, it’s called a method.

Upload: glenys

Post on 12-Jan-2016

50 views

Category:

Documents


0 download

DESCRIPTION

Chapter 4 Functions and methods :. General syntax: return_type function_name (par 1 , par 2 ,…, par n ) Each should contain comments. If it’s associated with a class, it’s called a method. Always write the functions with reuse in mind . Keep focus specific - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 4 Functions and methods :

Chapter 4 Functions and methods:

General syntax:

return_type function_name(par1, par2,…,parn)

Each should contain comments.If it’s associated with a class, it’s called a method.

Page 2: Chapter 4 Functions and methods :

Always write the functions with reuse in mind.

Keep focus specificFunction should NOT combine two or more tasks!!!! This limits their use by those who want one or the other.If function is to calculate and return a value, don’t display it.If a function is to display a value, calculate it elsewhere.

Page 3: Chapter 4 Functions and methods :

If a function is to error check a value before performing an action, do not print error messages(p. 175).Be cautious about catching exceptions in functions.Usually means functions are short.

Page 4: Chapter 4 Functions and methods :

return statement:function ends when return is executed. Specified value is returned and used in context where the function call is made. A return statement must be reachable for every possible condition. Value returned must be consistent with declared function type.Exception: If function is type void then no value is returned. Such functions are sometimes called procedures.

Page 5: Chapter 4 Functions and methods :

Predicate: function that returns a true or false.

Use meaningful names for functions and parameters. Follow standard conventions.Creativity in design is good. Creativity in defining names is not.If functions are class methods, then the header file must be included.

Page 6: Chapter 4 Functions and methods :

What is the problem with this?

#include <iostream>

using namespace std;

int main()

{

double x, y;

cin >> x;

y = half(x);

cout << y;

return 0;

}

double half(double x)

{

return 0.5*x;

}

Page 7: Chapter 4 Functions and methods :

If non-class functions are included with main then

functions signatures (sometime called prototypes) or implementations must appear BEFORE they are invoked.A function implementation may appear AFTER it is invoked (or in another file) if function signatures appear before or in an included header file. See syntax and example on p. 174.If not done, different compilers may respond differently.

Page 8: Chapter 4 Functions and methods :

All parameters are (by default) pass by value. Note the difference from Java. However, arrays are an exception to this.Reference parameters: Explain and show difference between

void swap (int x, int y){ int temp; temp = x; x = y; y = temp;}

and

void swap (int& x, int& y){ int temp; temp = x; x = y; y = temp;}

Page 9: Chapter 4 Functions and methods :

Any type can be reference or value. Note difference from java. This is IMPORTANT!

NOTE: This does not work in C. This is a C++ extension of C.

Deciding which variables are reference and which are value is a design issue.

Page 10: Chapter 4 Functions and methods :

In standard C, pass by reference was done using:void swap (int* x, int* y){ int temp; temp = *x; *x = *y; *y = temp;}

However, if a and b were type int, then the call had to look like

swap(&a, &b);

Page 11: Chapter 4 Functions and methods :

& is the address operator in C.

It is the same operator used to indicate a pass-by-reference parameter in C++ (though it appears after the parameter in the method signature.

The multiple use of & is somewhat unfortunate and does cause confusion! Be careful!

Page 12: Chapter 4 Functions and methods :

const reference parameters:Value parameters have higher overhead (making copies of parameter). More of an issue if parameter is an object with many parts.Reference parameters allow an object to be changed.Issue: How to lower overhead AND protect an object from change.A const reference allows the parameter to be protected against change AND lowers overhead of passing.

Page 13: Chapter 4 Functions and methods :

const type& parameter_nameShow what happens if previous swap function is declared as

void swap (const int& x, const int& y)

Does NOT work in C!

Page 14: Chapter 4 Functions and methods :

Variable scope:Extends from its declaration to the end of the block it was declared in.Declared in main => scope is main.Declared in a function => scope is local to the function.Book mentions global variables. Declared prior to main and all functions. Accessible from within all. DO NOT USE! Can cause name conflicts.

Page 15: Chapter 4 Functions and methods :

Testing and debugging

Do example (Section 4.11) converting a number into a text string (for display on payroll checks). Download this program from the course web site and test it. For what integers does it fail?Do his walkthrough on p. 195.

Page 16: Chapter 4 Functions and methods :

Alternative to inputting data for testing: srand(time(0)); for (int i=1; i<100; i++) { n=rand() % 1000000;

cout << n << ": " << int_name(n) << endl; }

Page 17: Chapter 4 Functions and methods :

Can be useful, but a less controlled test procedure.

DO NOT confuse quantity of test data with quality of test data

Page 18: Chapter 4 Functions and methods :

For functions, establish clear preconditions for each parameter and use exceptions to enforce them. NOTE: This can apply to constructors as well.

Page 19: Chapter 4 Functions and methods :

Chapter 3 Flow control:

if statements – pretty much like java. Look at examples starting on p. 103.Make sure brackets are aligned. This is a readability aid.The if/else statement -- Same as Java.

Page 20: Chapter 4 Functions and methods :

Do the selection operator. p. 104. Give examples. It’s confusing syntax but you need to be aware of it.NOTE: What does the following do?l = a>b?a>c?a:c:b>c?b:c;

Relational operators – same as java.

Page 21: Chapter 4 Functions and methods :

Test run the following code. What is wrong?

int x; cin >> x; if (x=1)

cout << "X is equal to 1" << endl; cin.get(); exit (0);

Be careful not to confuse = and ==. C++ will accept either! Result unpredictable.

Page 22: Chapter 4 Functions and methods :

Consider this example#include <iostream>#include <math.h>using namespace std;int main(){double x, sum;x = 0;sum = 0;while (x != 1.0){

x = x + 0.1;sum = sum + x;

}cout << " The sum is " << sum << endl;cin.get();return 0;}

Page 23: Chapter 4 Functions and methods :

Note: advanced tip-difference between errors and warnings. Must eliminate errors. Should eliminate warnings.

Comparing two float type numbers for equality can be a problem.

Page 24: Chapter 4 Functions and methods :

Example, implement the following code (don’t forget to #include <cmath>:

float x, y, z; cout << " Enter a number";

cin >> x; y=sqrt(x); z=y*y; cout << "x is " << x << "and z is " << z << endl; if (x==z)

cout << "x and z are equal" << endl; else

cout << "x and z are Not equal" << endl;

Page 25: Chapter 4 Functions and methods :

Look at ordering of multiple conditions from page 109-10. Can produce incorrect results.See the switch statement. See highlighted note on page 111.Notes on nesting ifs and dangling elses. Note example on page 112.Nested branches (p. 112). Discuss nested branches vs. conditions with compound conditions.

Page 26: Chapter 4 Functions and methods :

Example logic to compute postage costs

$5 to any of the 48 contiguous states

$7.50 to Alaska (AK)

$10 to Hawaii (HI)

$20 to any foreign country.

Page 27: Chapter 4 Functions and methods :

Is this OK? if (country == "USA")

if (state == "HI")

charge = 10.00;

else

if (state == "AK")

charge = 7.50;

else

charge = 5;

else

charge = 20.00;

Page 28: Chapter 4 Functions and methods :

How about this?

if (country == "USA") && (state == "HI")

charge = 10.00;

if (country == "USA") && (state == “AK")

charge = 7.50;

If (country == “USA”) && (state != “HI)

&& (state != “AK)

charge = 5;

If (country != “USA”)

charge = 20.00;

Page 29: Chapter 4 Functions and methods :

Create test data for example on p. 113. (See also sections 4.14 And 4.15)

positive cases. Legitimate data you expect the program to handle.negative cases: data you expect the program to reject.boundary cases: specific values used in conditions.Account for ALL possible combinations.

Page 30: Chapter 4 Functions and methods :

test harnessused to feed inputs to a function/method. Values can come from user inputs, values generated in a loop, or randomly generated values.

Page 31: Chapter 4 Functions and methods :

How do you know when output is correct?

May have to verify by hand calculation!!

Tedious but necessary. Sometimes you can rely on other previously tested methods. i.e. compare values returned by your own square_root function with those returned by sqrt().

Page 32: Chapter 4 Functions and methods :

In-class program: Calculate gross tax given:

0% on first $2005% on next $10010% on the next $20015% on the restReduce by $10 for each deduction up to a maximum of 6.How many different sets of test data would you generate?

Page 33: Chapter 4 Functions and methods :

Compound conditions.EX: if ( x==1 || x==2 && y==2)Which pairs of values make this true?

x=1 and y=3x=3 and y=2

Compound conditions (&& for and; || for OR). Best to NOT mix && and || operations unless you really know what you are doing)

Page 34: Chapter 4 Functions and methods :

Example: x==0 || 1/x<1. What happens if x is 0?

Compound conditions computed using lazy evaluation. Evaluate conditions (left to right) until the truth is determined. This means that all conditions may NOT be tested.

May not always be true with other languages and compilers! Care is needed!

Page 35: Chapter 4 Functions and methods :

Look at

cin >> x;

if ( x != 0 || x != 1)

cout << x << " bad input " << endl;

else

cout << x << " input is OK " << endl;

What values ofor x make this true?

Page 36: Chapter 4 Functions and methods :

Describe DeMorgans laws and relate to the previous example.

The condition that is ALWAYS true. This is the same as

if (!(x==0 && x==1).

Page 37: Chapter 4 Functions and methods :

While loops: pretty much the same as in Java.A few examples on page 123-4.Watch out for infinite loops.

Page 38: Chapter 4 Functions and methods :

Describe the for loop. Just like Java. Can declare variable in the for loop (p. 125). In this case the variable scope is the loop body.Note the tips and errors on page 128-130.Also a do loop. Compare it with the while loop.

Page 39: Chapter 4 Functions and methods :

Input validation: Note example on page 133. What if non-digits were entered?cin.fail() will return true if non-digits were typed but the data stream should contain digits.Using cin as a condition is the opposite of cin.fail() (example on p. 134)

Page 40: Chapter 4 Functions and methods :

Boolean variables and the the loop and a half issue on page 135.

Discuss end of file checking (cin.eof()) on p. 137.

Clearing the failure state of a stream (cin.clear()) on p.138.

Page 41: Chapter 4 Functions and methods :

Loop invariant (Important for proving program correctness, something not done in previous courses): assertion that is true every time a loop condition is tested. Can be useful in proving correctness of loop activity. Example: clever algorithm!!

r=1; b=a; i=n;while (i>0){

if (i%2==0){

b=b*bi=i/2

}else{

r=r*bi–-

}}

will always calculate an. (a and n are positive integers).

Page 42: Chapter 4 Functions and methods :

Claim: loop invariant is r*bi=an

Proof: True when loop starts. Next: Let r’, b’, and i’ be the new r, b, and i after one iteration of the loop. Need to show r’*b’i’=an:

Page 43: Chapter 4 Functions and methods :

Suppose: i%2==0 Suppose: i%2 !=0

Let b’ = b*b and i’ = i/2.

r*(b’)i’ = r*(b*b)i/2 = r*b2(i/2) = r*bi = an

Let r’ = r*b and i’ = i--

r’*bi’ = r*b*b(i-1) = r*bi = an

Page 44: Chapter 4 Functions and methods :

Discuss simulations, random numbers, pseudo random numbers, and seeds. Do the Buffon Needle experiment (p. 142) and a dice or card game simulation.Other examples on p. 143