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

Slides:



Advertisements
Similar presentations
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Advertisements

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Functions 1. Example: Power, Square Root and Absolute values of a number #include … float num; float power, squareRoot, absolute; cout
1 C++ Functions. // The function computes and returns the gross pay // based on the pay rate and hours. Hours over // 40 will be paid 1.5 times the regular.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
CS 1400 Chap 6 Functions. Library routines are functions! root = sqrt (a); power = pow (b, c); function name argument arguments.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
1 Chapter 9 Scope, Lifetime, and More on Functions.
Functions g g Data Flow g Scope local global part 4 part 4.
CSC 107 – Programming For Science. Today’s Goal  Discuss writing & using functions  How to declare them, use them, & trace them  Could write programs.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 6: Functions Starting Out with C++ Early Objects
1 CS 1430: Programming in C++. 2 Input: Input ends with -1 Sentinel-Controlled Loop Input: Input begins with.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
1 CS 1430: Programming in C++. 2 Literal Values Literal values of int Literal values of float
CPS120: Introduction to Computer Science Functions.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
1 C++ Loops Sentinel Controlled Count Controlled EOF Controlled.
Functions g g Data Flow g Scope local global part II g Global Resolution Operator part II.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
1 MODULAR DESIGN AND ABSTRACTION. 2 SPECIFYING THE DETAILS OF A PROBLEM INTO A RELATED SET OF SMALLER PROBLEMS.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
1 CS 1430: Programming in C++. 2 Find Max, Min, Average of m Sections Max, Min and Average of each section Max, Min and Average of all sections together.
1 CS 1430: Programming in C++. Quiz Functions Function Prototype float sqrt(float x); Function name, type, parameter and parameter type Function.
1 CS 1430: Programming in C++. 2 C++ Loops Sentinel Controlled Count Controlled EOF Controlled.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
1 CS 1430: Programming in C++. 2 Input: Input ends with -1 Sentinel-Controlled Loop Input: Input begins with.
1 Chapter 9 Scope, Lifetime, and More on Functions.
CS 1430: Programming in C++ Function Design 1. Good Functions Focusing on one thing Function name tells what it does sqrt(val) pow(base, exp) cin.eof()
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
1 Scope Lifetime Functions (the Sequel) Chapter 8.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
1 Program 2 Pseudo Code Read NumOfSongs of 1 st CD (Prime Read!) While not end of file Process CD Read NumOfSongs for next CD.
CS 1430: Programming in C++ 1. Test 2 Friday Functions Arrays For Loops Understand Concepts and Rules Memorize Concepts and Rules Apply Concepts and Rules.
1 Functions Function Prototype float sqrt(float x); Function name, type, parameter and parameter type Function Definition float sqrt(float x) { // compute.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
CS 1430: Programming in C++.
Arrays float Scores[9]; ? index: element // one dimensional array 1.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
Functions Procedural Abstraction Flow of Control INFSY 307 Spring 2003 Lecture 4.
Activation Record int main() { float allScores[MAX_ROWS][MAX_COLS]; int rows, cols; GetAllData(allScores, rows, cols);... } 1 void GetAllData(float a[][MAX_COLS],
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
CSC 107 – Programming For Science. Today’s Goal  Write functions that take & return values  How parameters declared and how we call functions  What.
Reference and Value Parameters Reference Parameters (&) The formal parameter receives the address of the actual parameter, and the function can read and.
Chapter 7: User-Defined Functions II
Scope of Variables The region of code where it is legal to reference (use) an identifier. Local Scope Global Scope Class Scope.
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
Value returning Functions
CS 1430: Programming in C++ No time to cover HiC.
Chapter 7: User-Defined Functions II
CS150 Introduction to Computer Science 1
Dynamic Memory.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
FOR statement a compact notation for a WHILE e.g. sumgrades = 0;
Scope Rules.
Presentation transcript:

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

2 Function Calls // Function prototype int Largest(int num1, int num2, int num3); // Function calls max = 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!

3 Function Calls // Function prototype float GrossPay(float payRate, float hours) cin >> hours >> rate; // Function calls gross = GrossPay(rate, hours); gross = GrossPay(hours, rate); // No Error // But incorrect result

4 Function Calls // Function prototype float sqrt(float x); // Function calls cout << “Square Root: ” << sqrt(delta); sqrt(delta); // Error: Must use the return value result = sgrt(delta); // Good!

5 Function Calls // Function prototype char myFunction(float param1, int param2, char param3); char charVal; charVal = myFunction(50.57, 48, ‘M’); // ValidInvalid charVal = myFunction(50.57, 48); // ValidInvalid charVal = myFunction(49, 50.57, ‘M’); // ValidInvalid charVal = myFunction(50.57, 48, “M”); // ValidInvalid myFunction(50.57, 48, ‘M’); // ValidInvalid cout << myFunction(50.57, 48, ‘M’); // ValidInvalid

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

7 VOID Functions void 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!

8 VOID Functions void 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; }

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

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

11 Example void DisplayMenu(); int main() { … DisplayMenu(); … } void DisplayMenu() { cout << “\nM or m to convert Meters to Inches” << … return; }

12 Scope of Variables The region of code where it is legal to reference (use) an identifier. Local Scope Global Scope Class Scope

13 Code Block Between 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; }

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

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!

16 Class Scope Later this semester!

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

18 Example float 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!

19 Precondition and Postcondition int 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!

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

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.

22 Program 2 Due 9:30 PM Today Grace date Friday Send to me Style Lab 4: Thursday

Exercise: Tracing Function Call Exercise\GrossPayFunction.doc 23

24 Tracing on GrossPay Input values: main() GrossPay() hours rate gross payRate hours pay ? ? ? ? ? ?