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.

Slides:



Advertisements
Similar presentations
Array. Convert Numbers in Different Base Systems Generate values to a series of numbers in different base systems: Base is between 2 and 9; Maximum number.
Advertisements

1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Student Data Score First Name Last Name ID GPA DOB Phone... How to store student data in our programs? 1.
PASSING PARAMETERS 1. 2 Parameter Passing (by Value) Parameters Formal Parameters – parameters listed in the header of the function Variables used within.
Functions 1. Example: Power, Square Root and Absolute values of a number #include … float num; float power, squareRoot, absolute; cout
CONTROL STRUCTURES: SEQUENTIAL, SELECTIVE, AND REPETITIVE
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Programming in C++ Lecture Notes 6 Void Functions (Procedures) Andreas Savva.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
1 CS 1430: Programming in C++. 2 Input: Input ends with -1 Sentinel-Controlled Loop Input: Input begins with.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters.
Chapter 5 Functions For All Subtasks. Void functions Do not return a value. Keyword void is used as the return type in the function prototype to show.
1 CS 1430: Programming in C++. 2 Literal Values Literal values of int Literal values of float
1 CS 1430: Programming in C++. 2 IF Statement if (cond) statement //Next statement if (cond) { statement1 statement2 … } //Next statement.
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
Passing Data - by Reference Syntax && double Pythagorus(double &, double &); Pythagorus(height, base); & & double Pythagorus(double& a, double& b) function.
111/15/2015CS150 Introduction to Computer Science 1 Summary  Exam: Friday, October 17,  Assignment: Wednesday, October 15, 2003  We have completed.
1 C++ Loops Sentinel Controlled Count Controlled EOF Controlled.
Input a number #include using namespace std; int main() { int num; cout num; return 0; }
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
Lecture 4 Function example. Example1 int max (int a, int b) { int c; if (a > b) c = a; else c = b; return (c); } void main ( ) {int x, y; cin>>x>>y; cout.
Quiz // // The function exchanges the two parameters. // Param: ( ) // Param:
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
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.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Data Types Storage Size Domain of all possible values Operations 1.
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.
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
Class Method Read class Student { private: string id; string firstName, lastName; float gpa; public: // Will the method change any data members? // Yes!
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.
User-Defined Functions (cont’d) - Reference Parameters.
1 Functions Function Prototype float sqrt(float x); Function name, type, parameter and parameter type Function Definition float sqrt(float x) { // compute.
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],
Arrays float Scores[9]; ? index: element // one dimensional array 2.
Topic 4 Data Structures Program Development and Design Using C++, Third Edition.
Reference and Value Parameters Reference Parameters (&) The formal parameter receives the address of the actual parameter, and the function can read and.
CS 1430: Programming in C++ No time to cover HiC.
CS 1430: Programming in C++.
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.
CS 1430: Programming in C++.
Student Data Score First Name Last Name ID GPA DOB Phone ...
CS 1430: Programming in C++ Turn in your Quiz1-2 No time to cover HiC.
CS 1430: Programming in C++.
CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
CS 1430: Programming in C++ No time to cover HiC.
Value returning Functions
CS 1430: Programming in C++ No time to cover HiC.
CS150 Introduction to Computer Science 1
Counting Loops.
Standard Input/Output Stream
CS150 Introduction to Computer Science 1
CS 1430: Programming in C++.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
CS 1430: Programming in C++.
CS 1430: Programming in C++ No time to cover HiC.
Presentation transcript:

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

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

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);... } 4

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

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

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? 7

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

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

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

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

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 12

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 13

Tracing Functions Input: HiC Notes\HiC\GrossPayInOutFuns.cpp 14

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: 9:30 PM, Today Style! Name conversion Quiz 4-2 Due 5 pm Monday Program 3 Two points Quiz Wednesday Two points progress Lab Thursday Discuss Friday 16

17 Prog2 Winner // The new route is the winner if (totalDistance < minTotalDistance && numDeiveries > maxDeiveries) // update winnerNum, // minTotalDistance and maxDeiveries // No winner for now else if (totalDistance =< minTotalDistance || numDeiveries >= maxDeiveries) // update winnerNum to -1 // minTotalDistance and maxDeiveries // The previous winner still winner else // do nothing

18 Prog2 Winner if (totalDistance < minTotalDistance && numDeiveries > maxDeiveries)... // No winner for now else if (totalDistance =< minTotalDistance || numDeiveries >= maxDeiveries) { winnerNum = -1; minTotalDistance = -1; maxDeiveries = -1; } Incorrect! Not Style!

19 Prog2 Winner // No winner for now else if (totalDistance =< minTotalDistance || numDeiveries >= maxDeiveries) { winnerNum = -1; if (totalDistance < minTotalDistance) minTotalDistance = totalDistance; if (numDeiveries > maxDeiveries) maxDeiveries = numDeiveries; } Correct! Update your Prog2 and submit again!

20 Prog2 Winner: Another Way if (totalDistance < minTotalDistance && numDeiveries > maxDeiveries)... else { if (totalDistance =< minTotalDistance) { winnerNum = -1; minTotalDistance = totalDistance; } // No else ! if (numDeiveries >= maxDeiveries) { winnerNum = -1; maxDeiveries = numDeiveries; } }

21 Prog2 Winner: Another Way if (routeNum == 1) { distWinnerNum = routeNum; delWinnerNum = routeNum; minTotalDistance = totalDistance; maxDeiveries = numDeiveries; } else { if (totalDistance < minTotalDistance) { distWinnerNum = routeNum; minTotalDistance = totalDistance; } else if (totalDistance == minTotalDistance) { distWinnerNum = routeNum; } // else prev distWinnerNum still winner // same if – else if for delWinnerNum }

Exercise Tracing Functions with In and Out Parameters GrossPayInOutParam.doc 22

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