1 value returning functions // function prototype int largest(int num1, int num2, int num3);...

24
1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters // More examples float sqrt(float x); char myFunction(float param1, int param2, char param3);

Upload: anastasia-murphy

Post on 01-Jan-2016

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

1

Value Returning Functions

// Function prototype int Largest(int num1, int num2, int num3);

Function Name Type Parameters Type of parameters Formal parameters

// More examplesfloat sqrt(float x);char myFunction(float param1, int param2, char param3);

Page 2: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

2

Function Calls

// Function prototypeint Largest(int num1, int num2, int num3);

// Function callsmax = Largest(score1, score2, score3);// Must follow the prototype!// actual parameters are different from formal parameters

max = Largest(int score1, int score2, int score3);// Do not include type for actual parameters!

Page 3: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

3

Function Calls

// Function prototype

float GrossPay(float payRate, float hours)

cin >> hours >> rate;

// Function callsgross = GrossPay(rate, hours);

gross = GrossPay(hours, rate);// No Error// But incorrect result

Page 4: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

4

Function Calls

// Function prototypefloat sqrt(float x);

// Function callscout << “Square Root: ” << sqrt(delta);

sqrt(delta);// Error: Must use the return value

result = sgrt(delta);// Good!

Page 5: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

5

Function Calls// Function prototypechar myFunction(float param1, int param2, char param3);

char charVal;

charVal = myFunction(50.57, 48, ‘M’);// Valid Invalid

charVal = myFunction(50.57, 48);// Valid Invalid

charVal = myFunction(49, 50.57, ‘M’);// Valid Invalid

charVal = myFunction(50.57, 48, “M”);// Valid Invalid

myFunction(50.57, 48, ‘M’);// Valid Invalid

cout << myFunction(50.57, 48, ‘M’);// Valid Invalid

Page 6: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

6

VOID Functions

Write a C++ function to display max, min and average.

Function name DisplayResult

Function type void (does not return any value)

Function parameters How many? max, min, avg Type of each parameters int, int, float float, float, float

void DisplayResult(float avg, float max, float min);

Page 7: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

7

VOID Functionsvoid DisplayResult(float avg, float max, float min);

int main() { float score, avg, highest, lowest; int numScores, loopCount = 0;

// input scores

// Compute avg, highest and lowest

// output results DisplayResult(avg, highest, lowest);

return 0; }

// Decompose a program into smaller functions// Programming Rule: each function can have at most 30 lines!

Page 8: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

8

VOID Functionsvoid DisplayResult(float avg, float max, float min);

// Programming Rules: Each function must have a description! // ------------------------------------------------------------// The function displays avg, max and min in required format. // ------------------------------------------------------------void DisplayResult(float avg, float max, float min) { cout << fixed << showpoint << setprecision(2);

cout << endl << endl << "The average score: " << setw(8) << avg << “.\n” << "The highest score: " << setw(8) << max << “.\n” << "The lowest score : " << setw(8) << min;

// return control, no value return; }

Page 9: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

9

Functions without Parameters void UserInstruction();

int main() { float score, avg, highest, lowest; int numScores, loopCount = 0;

UserInstruction();

// input

// process

DisplayResult(avg, highest, lowest);

return 0; }

Page 10: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

10

// Programming Rules: Each function must have a description!

// -----------------------------------------------------// The function displays user instructions. // -----------------------------------------------------void UserInstruction() { cout << endl << endl << "The program process all scores of one section " << endl << "of a class. The first input is the number of " << endl << "scores. All scores must be in the range of " << endl << "0.0 and 60.0, inclusive." << endl << endl;

return; }

Page 11: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

11

Examplevoid DisplayMenu();

int main(){ … DisplayMenu(); …}

void DisplayMenu(){ cout << “\nM or m to convert Meters to Inches” << …

return;}

Page 12: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

12

Scope of Variables

The region of code where it is legal to reference (use) an identifier.

• Local Scope

• Global Scope

• Class Scope

Page 13: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

13

Code BlockBetween a pair of matching braces The body of a function

int main(){ int alpha = 10;

// A block for if statement if (alpha > 3) { int n; cin >> n; alpha += 3; } return 0;}

Page 14: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

14

Local Scope

The scope of an identifier declared inside a block extends from the point of declaration to the end of that block.

int main()

{

int alpha = 10;

// A code block

if (alpha > 3)

{

int num;

cin >> num;

alpha += num;

}

cout << “num = ” << num;

// Run time error!

return 0;

}

Page 15: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

15

Global Scope

The scope of an identifier declared outside all functions (and classes) extends from the point of declaration to the end of the entire source file.

Programming Rules:

No global variables!

Page 16: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

16

Class Scope

Later this semester!

Page 17: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

17

Scope of Function Parameters

• Formal parameters

Local scope

Same as local variable

Cannot reference it outside the function

Receive values on function call

• Actual parameters (no global variables)

Local scope

Cannot reference it inside the called function

Page 18: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

18

Examplefloat DoIt(int num, char op);

int main(){ int base; float result; char choice;

cout << “Enter a number: ”; cin >> base; cout << “C for Cube and S for Square Root: ”; cin >> choice;

while (choice != ‘C’ && choice != ‘S’) { cout << “C for Cube and S for Square Root: ”; cin >> choice; }

result = DoIt(base, choice);

cout << “The result: ” << result;

return 0;}

// ----------------------------// Precondition: op is ‘C’ or ‘S’// Postcondition: the cube of// num is computed when op is// ‘C’, and square root of num// is computed when op is ‘S’.// ------------------------------float DoIt(int num, char op){ if (op == ‘C’) result = pow(num, 3); else result = sqrt(num); return result;}

// What is wrong?// Result not declared in the // function!

Page 19: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

19

Precondition and Postconditionint DoIt(int num, char op);

int main(){ int base; float result; char choice;

cout << “Enter a number: ”; cin >> base; cout << “C for Cube and S for Square: ”; cin >> choice;

while (choice != ‘C’ && choice != ‘S’) { cout << “C for Cube and S for Square: ”; cin >> choice; }

result = DoIt(base, choice);

cout << “The result: ” << result;

return 0;}

// ------------------------------// Precondition: op is ‘C’ or ‘S’// Postcondition: the cube of// num is computed when op is// ‘C’, and square root of num// is computed when op is ‘S’.// ------------------------------int DoIt(int num, char op){ float result; if (op == ‘C’) result = pow(num, 3); else result = sqrt(num); return result;}

// The two variables // result have the same // name, but different!

Page 20: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

20

Parameter Names

• Meaningful names

• Formal and actual parameters can have the same name

• They are different variables in different scopes

• Normally they have different names

Page 21: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

21

Lifetime of a Variable

• Lifetime

The period of time during program execution when an identifier has memory allocated to it.

• Automatic variables

A variable for which memory is allocated and deallocated when control enters and exits the block it is declared.

• Static variables

A variable for which memory remains allocated throughout the execution of the entire program.

Page 22: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

22

Program 2

• Due 9:30 PM Today• Grace date Friday

Send email to me• Style

• Lab 4: Thursday

Page 23: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

Exercise: Tracing Function Call

Exercise\GrossPayFunction.doc

23

Page 24: 1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters

24

Tracing on GrossPay

Input values: 10 45

main() GrossPay() hours rate gross payRate hours pay

? ? ? ? ? ?

45 10

10 45

475

475