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

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

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
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
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 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
CS 1400 Chap 6 Functions. Library routines are functions! root = sqrt (a); power = pow (b, c); function name argument arguments.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Functions g g Data Flow g Scope local global part 4 part 4.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
FUNCTIONS (a) Value returning e.g. int main() ….…. return 0; (b) Void (returning) no return statements example To print this message **** ** Welcome.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
1 C++ Loops Sentinel Controlled Count Controlled EOF Controlled.
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
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
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.
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.
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 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.
Reference and Value Parameters Reference Parameters (&) The formal parameter receives the address of the actual parameter, and the function can read and.
Review 1.
MT262A Review.
Variables A piece of memory set aside to store data
Arrays Part-1 Armen Keshishian.
New Structure Recall “average.cpp” program
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++ No time to cover HiC.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CS 1430: Programming in C++ No time to cover HiC.
CS150 Introduction to Computer Science 1
Counting Loops.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
CS150 Introduction to Computer Science 1
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Let’s all Repeat Together
Let’s all Repeat Together
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Functions Imran Rashid CTO at ManiWeber Technologies.
Arrays, Part 1 of 2 Topics Definition of a Data Structure
Arrays, Part 1 of 2 Topics Definition of a Data Structure
CS150 Introduction to Computer Science 1
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich YangQ@uwplatt.edu Ask questions one by one and stopped at slide 18

Reference and Value Parameters Reference Parameters (&) The formal parameter receives the address of the actual parameter, and the function can read and update the value of the actual parameter. Value Parameters (No &) The formal parameter receives (a copy of) the value of the actual parameter, and the function can use the value, but can NOT change the value of the actual parameter. How to pass the parameters?

In, Out, InOut Parameters The function uses the value of the actual parameter. Out The calling function gets the new or updated value of the formal parameter. (a function can only return one value using the return statement) InOut Both In and Out Why do we pass parameters? Nothing to do with the return statement.

Function Parameters For each parameter 1. Figure out In, Out or InOut 2. Pass by value or Pass by reference In Pass by value (value parameter) (Does not let the function modify the values without &) Out Pass by reference (reference parameter with &) InOut

In, Out, InOut Parameters Passing parameters at function call Nothing to do with what the function does. In Parameters Not input inside the function Out Parameter Not output inside the function

In, Out, InOut Parameters // ----------------------------------------------------------- // The function inputs payRate and hoursWorked and // pass both values back to calling function // Parameters: (out, out) void GetInput(float& payRate, float& hoursWorked) { cout << “Enter the pay rate: ”; cin >> payRate; cout << “Enter the hours: ”; cin >> hoursWorked; } The function does input. The parameters are OUT.

In, Out, InOut Parameters // ------------------------------------------------------------ // The function displays avg, max and min in required format. // Parameters: (In, In, In) 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; } The function does output. The parameters are IN.

Programming Rules Function description Specify IN, OUT, or INOUT parameters // ----------------------------------------------------------- // The function computes and returns the gross pay based on // the pay rate and hours. Hours over will be paid 1.5 times // the regular pay rate. // Parameters: (in, in) float GrossPay(float payRate, float hours) { // Function body } // The function inputs payRate and hoursWorked and // pass both values back to calling function // Parameters: (out, out) void GetInput(float& payRate, float& hoursWorked)

Use Reference parameters only when necessary! Programming Rules Use Reference parameters only when necessary! // ----------------------------------------------------------- // 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) { // Function body } // It will work. // Lose points! // The function inputs payRate and hoursWorked and // pass both values back to calling function. // Parameters: (out, out) void GetInput(float payRate, float hoursWorked) // Will compile and run. // Won’t get values in the calling function.

Value Parameter What can the actual parameter be? A VALUE! Literal value (magic number) Variable (initialized!) Expression (with all variables initialized)

Function Calls // Function Prototype float sqrt(float x); root1 = (-coefB + sqrt(delta)) / (2 * coefA); // Parameter is variable delta with a value cout << “The square root of 10 is “ << sqrt(10); // Parameter is literal value 10 Value = sqrt (coefB * coefB - 4 * coefA * coefC); // Parameter is an expression // with coefA, coefB and coefC initialized

float GrossPay(float payRate, float hours); cin >> hours >> rate; gross = GrossPay(rate, hours); // Valid function call? gross = GrossPay(rate, 35.5); // Holiday hours gross = GrossPay(2 * rate, hours);

Uninitialized Variable float GrossPay(float payRate, float hours); float gross, hours, rate; // Call function with uninitialized variable gross = GrossPay(rate, hours); VS Error: Run-Time Check Failure #3 - The variable ‘hours' is being used without being initialized.

Reference Parameter What can the actual parameter be? AN ADDRESS! Literal value: NO Expression : NO Variable : YES (initialized or uninitialized) void GetInput(float& rate, float& hours); float rate, hours; GetInput(rate, hours); // Valid function call? GetInput(rate, 35); GetInput(2 * rate, hours);

Actual Parameter Does the actual parameter change its value when the corresponding formal parameter changes its value? Value Parameter NO! Reference Parameter YES!

Function Calls void myFun(float num, int& count, float& total); float score, sum = 0; int ScoreCount = 0; myFun(score, ScoreCount, sum); // Q: Valid function call? myFun(55.5, ScoreCount, sum); cin >> score; // for all following questions myFun(pow(score, 2), ScoreCount, sum); myFun(score, 2 * ScoreCount, sum); myFun(score, ScoreCount, 100); cout << myFun(score, ScoreCount, sum); // Q: Valid statement?

Function Calls void myFun(float num, int& count, float& total); score = 55.0; sum = 100.5; ScoreCount = 5; myFun(score, ScoreCount, sum); // Q: What is the value after the function call? // score 5 55.0 100.5 unknown // sum 5 55.0 100.5 unknown // ScoreCount 5 55.0 100.5 unknown

Function Calls char goodFun(float& num, char choice); char input, output; float amount = 50.5; input = goodFun(amount, ‘A’); // Q: Valid function call? input = goodFun(amount, output); input = goodFun(100, ‘A’); cout << goodFun(amount, goodFun(amount, ‘A’)); // Q: Valid statement? goodFun(amount, ‘A’);

// Parameters: (?, ?) void WhoseFun(int param1, int& param2) { param2 = 3; param2 += param1; cin >> param1; return; } // param1: In, Out, InOut? // param2: In, Out, InOut?

void WhoseFun(int param1, void main() { int num1; int num2; num1 = 5; // num1 = ? // num2 = ? WhoseFun(num1, num2); return; } // Parameters: (?, ?) void WhoseFun(int param1, int& param2) { param2 = 3; param2 += param1; cin >> param1; // 9 return; } // param1: In, Out, InOut // param2: In, Out, InOut

void WhoseFun(int param1, void main() { float num1; int num2; num1 = 5; num2 = 10; // num2 has a value! WhoseFun(num1, num2); // num1 = ? // num2 = ? return; } // Parameters: (?, ?) void WhoseFun(int param1, int& param2) { param2 = 3; param2 += param1; cin >> param1; // 9 return; } // param1: In, Out, InOut // param2: In, Out, InOut

// Parameters: (?, ?) int WhichFun(int param1, int& param2) { if (param2 > 0) param1 = sqrt(param2); param2 = 3; param2 += param1; cin >> param1; return param1; } // param1: In, Out, InOut // param2: In, Out, InOut // Is it a good function? // NO: Return value and InOut parameter! // Programming Rule!

int main() { float score, highest, lowest; int scoreCount = 0; cin >> score; while (!cin.eof()) if (scoreCount == 0) highest = score; lowest = score; } else if (score > highest) if (score < lowest) scoreCount ++; // Display result return 0; // Task: Use a function to update highest and lowest.

Use a function to update highest and lowest Function Prototype Name: UpdateMaxMin Type: void Parameters: How many? score In, Out, InOut? max min Pass by Value or Pass by Reference?

// ------------------------------------------------- // The function uses the value of num to update the // values of max and min. // Parameters: ( In , InOut , InOut ) void UpdateMaxMin(float num, float& max, float &min) { if (num > max) max = num; if (num < min) min = num; return; }

void UpdateMaxMin(float value, float& max, float& min); int main() { float score, highest, lowest; int scoreCount = 0; cin >> score; while (!cin.eof()) if (scoreCount == 0) highest = score; lowest = score; } else UpdateMaxMin(score, highest, lowest); scoreCount ++; // Display result return 0;