1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich

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: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, 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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
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.
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 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters.
1 CS 1430: Programming in C++. 2 Literal Values Literal values of int Literal values of float
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.
#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.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
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++. 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 Scope Lifetime Functions (the Sequel) Chapter 8.
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.
CHAPTER 8 Scope, Lifetime, and More on Functions.
CS 1430: Programming in C++.
Arrays float Scores[9]; ? index: element // one dimensional array 1.
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],
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
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.
User-Written Functions
Chapter 7: User-Defined Functions II
User-Defined Functions
CS 1430: Programming in C++.
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
Chapter 7: User-Defined Functions II
CS150 Introduction to Computer Science 1
Functions Imran Rashid CTO at ManiWeber Technologies.
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;
Functions Chapter No. 5.
Scope Rules.
Presentation transcript:

1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich

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

3 Code Block Between a pair of matching braces. For example, 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; }

4 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 << alpha; // OK? cout << num; // OK? // Run time error! return 0; }

5 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!

6 Class Scope Later this semester!

7 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

8 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!

9 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!

10 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

11 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.

12 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 pay rate. float GrossPay(float payRate, float hours) { float total; if (hours > REG_HOURS) total = (hours - REG_HOURS)* OVER_TIME * payRate + REG_HOURS * payRate; else total = hours * payRate; return total; } // No input for payRate and hours // Parameters receive values on function call! 13

Passing Parameters const float REG_HOURS = 40.0; const float OVER_TIME = 1.5; int main() { float hours, rate, gross; cin >> rate >> hours; // rate: 12.5 // hours: 50 gross = GrossPay(rate, hours); // display result return 0; } float GrossPay(float payRate, float hours) { float total; if (hours > REG_HOURS) total = (hours - REG_HOURS) * OVER_TIME * payRate + REG_HOURS * payRate; else total = hours * payRate; return total; } main() GrossPay() Function call Passing parameters Returning to main() With return value 14

IN Parameter The value of the actual parameter is passed into the function and assigned to the formal parameters. float GrossPay(float payRate, float hours); int main() {... cin >> rate >> hours; // rate: 12.5 // hours: 45.5 gross = GrossPay(rate, hours);... } 15

IN Parameters int Largest(int num1, int num2, int num3); cin >> score1 >> score2 >> score3; max = Largest(score1, score2, score3); void DisplayResult(float avg, float max, float min); // Input scores and compute the highest, // lowest and average DisplayResult(avg, highest, lowest); // The function does output, but IN parameters! float sqrt(float x); 16

Function Parameters In The value of the actual parameter is passed into the function and assigned to the formal parameter. Out The value of formal parameter is passed out of the function and assigned to the actual parameter. InOut Both In and Out. 17

float GrossPay(float payRate, float hours); int main() { float hours, rate, gross; // Input values in main() cin >> rate >> hours; gross = GrossPay(rate, hours); // display result return 0; } // Q: Can we use a function to input rate and hours? 18

Write a function to input rate and hours Function Prototype Name: GetInput Type: void Cannot pass two values using the return statement Parameters: rate (payRate), hours (hoursWorked) type: float (Passing values back to calling function) (OUT parameters!) (&) void GetInput(float& payRate, float& hoursWorked); 19

float GrossPay(float payRate, float hours); void GetInput(float& payRate, float& hoursWorked); int main() { float hours, rate, gross; // Call function GetInput() to get two values GetInput(rate, hours); // Call function GrossPay to get one value gross = GrossPay(rate, hours); // display result return 0; } 20

Function Definition // // The function inputs payRate and hoursWorked and // pass both values back to the calling function. // Parameters: (out, out) // void GetInput(float& payRate, float& hoursWorked) { cout << "Enter pay rate: "; cin >> payRate; cout << "Enter hours: "; cin >> hoursWorked; return; } // The function does input with prompt, but OUT parameters! // How can it pass two values back? // Out Parameters: & // Statement return can pass only one value back! 21

// // 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 pay rate. // Parameters: (in, in) // float GrossPay(float payRate, float hours) { if (hours > REG_HOURS) payRate = (hours - REG_HOURS) * OVER_TIME * payRate + REG_HOURS * payRate; else payRate = hours * payRate; return payRate; } // No local variable // payRate is used to store the result 22

Reference and Value Parameters float GrossPay(float payRate, float hours); void GetInput(float& payRate, float& hoursWorked); Value parameter: No & The value of actual parameter is passed to the formal parameter Reference Parameter: & The address of actual parameter is passed to the formal parameter Does the actual parameter change its value when the corresponding formal parameter changes its value? Value parameter (no &): NO Reference parameter (&): YES 23

Value and Reference Parameters const float REG_HOURS = 40.0; const float OVER_TIME = 1.5; int main() { float hours, rate, gross; GetInput(rate, hours); gross = GrossPay(rate, hours); // display result return 0; } float GrossPay(float payRate, float hours) { if (hours > REG_HOURS) payRate = (hours - REG_HOURS) * OVER_TIME * payRate + REG_HOURS * payRate; else payRate = hours * payRate; return payRate; } main() GetInput() void GetInput(float& payRate, float& hoursWorked) { cout << "Enter pay rate: "; cin >> payRate; cout << "Enter hours: "; cin >> hoursWorked; return; } GrossPay() Passing parameters Passing parameters Addresses of rate and hours Return control With value Return control 24

Tracing Functions Input: GetInput(rate, hours); // Reference parameters gross = GrossPay(rate, hours);// Value parameters main() GetInput() GrossPay() hours rate gross & payRate & hoursWorked hours payRate ? ? ? ? ? ? ? Addr of Addr of rate hours

Schedule Program 2 Grace Time: 10 PM, Friday Style! Name conversion Quiz 4-2 Due 10 pm Thursday (Lab5: next week) Program 3 –Optional groups –Two students each group –Sign group by Friday 26