Functions—Part I. Slide 2 Where are we now? Simple types of variables 3 program structures cin(>>)/cout(<<) Array Functions (subprograms) (File I/O) Midterm:

Slides:



Advertisements
Similar presentations
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Advertisements

Functions. COMP104 Functions / Slide 2 Introduction to Functions * A complex problem is often easier to solve by dividing it into several smaller parts,
Modular Programming With Functions
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Programming Functions: Passing Parameters by Reference.
Introduction to Functions Programming. COMP102 Prog Fundamentals I: Introduction to Functions /Slide 2 Introduction to Functions l A complex problem is.
Chapter 5 Functions.
Computer Science 1620 Loops.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
Writing and Testing Programs Drivers and Stubs Supplement to text.
Chapter 6: User-Defined Functions I
Functions:Passing Parameters by Value Programming.
CS 117 Spring 2002 Functions Hanly - Chapter 5 Friedman-Koffman - Sections & Chapter 6.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 6: User-Defined Functions I.
Functions. COMP104 Lecture 13 / Slide 2 Review of Array: Bubble Sort for (j=0; j List[j+1]) swap(List[j], List[j+1]); }
CS 201 Functions Debzani Deb.
Top-Down Design with Functions 4 What do programmer’s (not programs!) use as input to the design of a program? –Documentation Problem definition Requirements.
Chapter 6: User-Defined Functions I
Functions. COMP104 Lecture 13 / Slide 2 Function Prototype * The function prototype declares the interface, or input and output parameters of the function,
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Function Part II: Some ‘advanced’ concepts on functions.
Pass by Reference. COMP104 Pass by Reference / Slide 2 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass.
CS 1400 Chap 6 Functions. Library routines are functions! root = sqrt (a); power = pow (b, c); function name argument arguments.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 7 Functions.
Programming Functions: Passing Parameters by Reference.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
CPS120: Introduction to Computer Science Functions.
USER-DEFINED FUNCTIONS. STANDARD (PREDEFINED) FUNCTIONS  In college algebra a function is defined as a rule or correspondence between values called the.
Functions. Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include using namespace std; int main() { int y=0; int partResult=1; for (int i=1;
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 6 User-Defined Functions I. Objectives Standard (predefined) functions What are they, and How to use them User-Defined Functions Value returning.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
CS Class 08 Today  Exercises  Nested loops  for statement  Built-in functions Announcements  Homework #3, group solution to in-class.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
CHAPTER 6 USER-DEFINED FUNCTIONS Made By- Kartik Belwal.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Introduction to Functions.  A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3: User-Defined Functions I
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
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.
Chapter 6: User-Defined Functions I
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Functions Chapter 5 CS12 - Computer Programming 1 Chapter 5.
User-Defined Functions
Functions.
Functions.
More ‘concepts’ on Function
Pass by Reference.
Chapter 6: User-Defined Functions I
CS 144 Advanced C++ Programming January 31 Class Meeting
Introduction to Functions
More ‘concepts’ on Function
Presentation transcript:

Functions—Part I

Slide 2 Where are we now? Simple types of variables 3 program structures cin(>>)/cout(<<) Array Functions (subprograms) (File I/O) Midterm: structured programming now

Slide 3 Review: Problem Solving Process * Define and analyze the problem n What is the input & output? n What constraints must be satisfied? n What information is essential? * Design an algorithm n What steps must be done? n Wirte down the solution steps in detail * Implement a program - programming or coding. * Compile, test, and debug the program - testing. * Document and maintain the program. Problem solving phase Implementation phase

Slide 4 Top-down analysis * A complex problem is often easier to solve by dividing it into several smaller parts (subproblems), each of which can be solved by itself. * This is called top-down programming. * Let’s take the example of Diamand drawing!

Slide 5 Example: Diamond Pattern * Input: nothing * Output: print out a diamond pattern * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Slide 6 Example: top-down analysis * Output: print out a diamond pattern n print out the upper half  upper triangular form n print out the lower half  lower triangular form

Slide 7 Example: upper triangular pattern * Upper triangular pattern: n row 1: print 4 spaces, 1 star; n row 2: print 3 spaces, 3 stars; n row 3: print 2 spaces, 5 stars; n row 4: print 1 space, 7 stars; n row 5: print 0 spaces, 9 stars; * * * * * * * * * * * * * * * * * * * * * * * * *

Slide 8 Example: top-down refinement * Refinement: n row 1: print (5-row) spaces, (2*row - 1) stars; n row 2: print (5-row) spaces, (2*row - 1) stars; n row 3: print (5-row) spaces, (2*row - 1) stars; n row 4: print (5-row) spaces, (2*row - 1) stars; n row 5: print (5-row) spaces, (2*row - 1) stars; * For each ‘row’ (more exactly from row 1 to 5), always do n Print 5-row spaces n Print 2*row-1 stars * It’s a loop: pseudo-code * * * * * * * * * * * * * * * * * * * * * * * * * int row; row=1; while(row<=5){ print 5-row spaces; print 2*row-1 stars; row=row+1; }

Slide 9 Example: algorithm int row, space, star; row=1; while(row<=5){ space=1; while(space<=5-row) { cout << " "; space=space+1; } star=1; while(star<=2*row-1) { cout << "*"; star=star+1; } cout << endl ; row=row+1; } int row; row=1; while(row<=5){ 5-row spaces; 2*row-1 stars; row=row+1; }

Slide 10 Introduction to Functions * The subproblems are solved by subprograms, called functions in C++.  main() then executes these functions so that the original problem is solved.

Slide 11 Advantages of Functions * separate the concept (what is done) from the implementation (how it is done). * make programs easier to understand. * make programs easier to modify. * can be called several times in the same program, allowing the code to be reused.

Slide 12 Function Input and Output Function Result Input parameters

Slide 13 C++ Functions * C++ allows the use of both pre- defined and user-defined functions.  Predefined functions (e.g., cin, cout, rand, etc.) are usually grouped into specialized libraries (e.g., iostream, cstdlib, cmath, etc.)

Slide 14 Mathematical Functions * #include * double log(double x) natural logarithm * double log10(double x) base 10 logarithm * double exp(double x) e to the power x * double pow(double x, double y) x to the power y * double sqrt(double x) positive square root of x * double ceil(double x) smallest integer not less than x * double floor(double x) largest integer not greater than x * double sin(double x), cos(double x), tan(double x), etc...

Slide 15 How to use a pre-defined function: Distance Between Two Points Output:distance Input: two points: (x1,y1), and (x2,y2) Distance = sqrt((x2-x1)*(x2-x1) + (y2- y1)*(y2-y1)) x1,y1, x2, y2 are input data, so we are done!

Slide 16 How to use a pre-defined function: Distance Between Two Points #include #include // contains sqrt() using namespace std; int main(){ double x1, y1, x2, y2; // coordinates for point 1 & 2 double dist; // distance between points cout << "Enter x & y coordinates of the 1st point: "; cin >> x1 >> y1; cout << "Enter x & y coordinates of the 2nd point: "; cin >> x2 >> y2; dist = sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1)); cout << "The distance is " << dist << endl; return 0; } They are also function calls!

Slide 17 How to define a function? * A function definition has following syntax: ( ){ }

Slide 18 * A function returns a single result (that’s the type of the function) * One of the statements in the function body should have the form: return ; (it’s good to use ONLY one at last!) * The value passed back by return should have the same type as the function.

Slide 19 Example: Absolute Value (1 st version) #include using namespace std; int absolute(int fx){ int abs; if (fx >= 0) abs=fx else abs = -fx; return abs; } int main(){ int x, y, diff,adiff; cout << "Enter two integers (separated by a blank): "; cin >> x >> y; diff = x – y; adiff=absolute(diff); cout << "The absolute difference between " << x << " and " << y << " is: " << adiff << endl; return 0; }

Slide 20 Function Prototype * The function prototype declares the interface, or input and output parameters of the function, leaving the implementation for the function definition. (It therefore separates the concept from the implementation!) * The function prototype has the following syntax: ( );

Slide 21  You can place a function definition in front of main(). In this case there is no need to provide a function prototype for the function, since the function is already defined before its use. * The function definition can be placed anywhere in the program after the function prototypes. * C++ programs usually have the following form: // include statements // function prototypes // main() function // user-defined functions

Slide 22 Absolute Value (2 nd version) #include using namespace std; int absolute (int);// function prototype for absolute() int main(){ int x, y, diff; cout << "Enter two integers (separated by a blank): "; cin >> x >> y; diff = absolute( x - y); cout << "The absolute difference between " << x << " and " << y << " is: " << diff << endl; return 0; } int absolute(int fx){ int abs; if (fx >= 0) abs=fx else abs=-fx; return abs; }

Slide 23 How to use or call a function? * A function call has the following syntax: ( ) n There is a one-to-one correspondence between the parameters in a function call and the parameters in the function definition.

Slide 24 Summary with Absolute Value Example #include using namespace std; int absolute (int);// function prototype for absolute() // int absolute (int fx); int main(){ int x, y, diff; cout << "Enter two integers (separated by a blank): "; cin >> x >> y; diff = x-y; diff = absolute(diff); cout << "The absolute difference between " << x << " and " << y << " is: " << diff << endl; return 0; } // Define a function to take absolute value of an integer int absolute(int fx) { int abs; if (fx >= 0) abs=fx; else abs= -fx; return (abs); } formal parameter final result of the function function call, argument

Slide 25 A function returns a single result, but a void type function does not return anything (but does something, a sub-program)! ‘Void’ type functions (‘main’ is just a function that has no formal parameters for the moment )

Slide 26 Example (void): Printing Cards  The main() program which calls printcard() #include using namespace std; void printcard(int);// function prototype int main(){ int c1, c2, c3, c4, c5; // pick cards... // print cards printcard(c1); printcard(c2); printcard(c3); printcard(c4); printcard(c5); // find score // print score }

Slide 27 * A function that prints the card (J) given the card number (11) as input: void printcard(int cardnum){ if(cardnum==1) cout << "A"; else if(cardnum>=2 && cardnum<=10) cout << cardnum; else if(cardnum==11) cout << "J"; else if(cardnum==12) cout << "Q"; else if(cardnum==13) cout << "K"; } (This is a void function - a function that does not return a value)

Slide 28 Example: Total length of a triangle Output: total-length Input: three points: A=(x1,y1), B=(x2,y2), and C=(x3,y3) Total-length = length(AB) + length(AC) + length(AB) Length(AB) = dist(A,B); Length(AC) = dist(A,C); Length(BC) = dist(B,C);

Slide 29 Example: Total length of a triangle #include using namespace std; double dist(double, double, double, double); int main(){ double x1, y1, // coordinates for point 1 x2, y2, // coordinates for point 2 x3, y3, // coordinates for point 3 l12,l23,l13,length; cout << "Enter x & y coordinates of the 1st point: "; cin >> x1 >> y1; cout << "Enter x & y coordinates of the 2nd point: "; cin >> x2 >> y2; cout << "Enter x & y coordinates of the 3rd point: "; cin >> x3 >> y3;

Slide 30 l12 = dist(x1,y1,x2,y2); l23 = dist(x2,y2,x3,y3); l13 = dist(x1,y1,x3,y3); length = l12 + l23 + l13; return 0; } // Function for computing the distance between 2 pts double dist(double fx1, double fy1, double fx2, double fy2) { double dist; dist = sqrt( (fx2-fx1)*(fx2-fx1) + (fy2-fy1)*(fy2-fy1) ); return dist; } // Function for computing the distance between 2 pts double dist(double x1, double y1, double x2, double y2) { double dist; dist = sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) ); return dist; } exactly the same! Two different variables How to communicate? Pass by value!

Pass by value

Slide 32 Passing parameters by Value * This is by default and desirable behavior! * An important fact to remember about parameter passing by value is that changes to the parameters inside the function body have no effect outside of the function. * You may think that calling parameters and formal parameters are just different variables.

Slide 33 Example 0 * For example, consider the following code: int sum(int a, int b){ a = a + b; return a; } void main(){ int x, y, z; x = 3; y = 5; z = sum(x,y); }  What is the value of x, y, and z at the end of the main() program?

Slide 34 * The answer: 3, 5, and 8.  Even though the value of parameter a is changed, the corresponding value in variable x does not change. * This is why this is called pass by value. * The value of the original variable is copied to the parameter, but changes to the value of the parameter do not affect the original variable. * In fact, all information in (local) variables declared within the function will be lost when the function terminates. * The only information saved from a pass by value function is in the return statement.

Slide 35 Example 1 * An example to show how the function does not affect a variable which is used as a parameter: // Test the effect of a function // on its parameter #include using namespace std; void Increment(int Number) { Number = Number + 1; cout << "The parameter Number is: " << Number << endl; }

Slide 36 void main() { int I = 10; //parameter is a variable Increment(I); cout << "The variable I is: " << I << endl; //parameter is a constant Increment(35); cout << "The variable I is: " << I << endl; //parameter is an expression Increment(I+26); cout << "The variable I is: " << I << endl; }

Slide 37

Slide 38 Example 2 // Print the sum and average of two numbers // Input: two numbers x & y // Output: sum - the sum of x & y // average - the average of x & y #include using namespace std; void PrintSumAve ( double, double ); int main ( ) { double x, y; cout << "Enter two numbers: "; cin >> x >> y; PrintSumAve ( x, y ); }

Slide 39 void PrintSumAve (double no1, double no2) { double sum, average; sum = no1 + no2; average = sum / 2; cout << "The sum is " << sum << endl; cout << "The average is " << average << endl; }

Slide 40  Data areas after call to PrintSumAve() :

Slide 41 Example 3 //Compute new balance at a certain interest rate //Inputs: A positive balance and // a positive interest rate //Output: The new balance after interest was posted #include using namespace std; double new_balance(double balance, double rate); /* Returns the balance in a bank account after adding interest. For example, if rate is 5.0, then the interest rate is 5% and so new_balance(100, 5.0) returns */

Slide 42 int main(){ double interest, balance; cout << "Enter balance (positive number): "; cin >> balance; if (balance <= 0.0) cout <<"Balance not positive; stopping" << endl; else { cout <<"Enter interest rate (positive number): "; cin >> interest; if (interest <= 0.0) cout << "Interest not positive; stopping" << endl; else cout <<"New balance = $" << new_balance(balance, interest)<< endl; } return 0; }

Slide 43 // New balance is computed as balance + balance * %rate double new_balance(double balance, double rate) { double interest_fraction, interest; interest_fraction = rate / 100; interest = interest_fraction * balance; return (balance + interest); }

Slide 44 Summary * Function parameters (like variables) * Function type (type of the function name) * Return statement (the last statement) n Finishes the function n Return the value to the caller * Understanding the ‘flow control’ between ‘main’ and a function * Communication: pass by value * Empty ‘void’ type

Slide 45 Input: formal parameters * Similar to (local) variables

Slide 46 Output: return statement * The final result (that should be returned to the calling expression), the end of the ‘sub-programme’ * Recommended to use only one ‘return’ as the last statement of the function (for good structure of the programmes) n It can in fact appear any places (close friends of ‘break’ and ‘continue’ n Example: int max(int a, int b) {if (a>b) return a; else return b;} or int max(int a, int b) {int m; if (a>b) m=a; else m=b; return m;} * The type should match that of the function

Slide 47 Function call: pass by value * Effective parameters (variables) and formal parameters (variables) are completely different * We just copy to or initialize the formal parameters from the effective parameters * ‘effective parameters’ are ‘originals’, and ‘formal parameters’ are ‘photocopies’! They are different.

Pass by Reference

Slide 49 Review on Pass by Value: #include using namespace std; void Increment(int Number){ Number = Number + 1; cout << "The parameter Number: " << Number << endl; } void main(){ int I = 10; Increment(I); // parameter is a variable cout << "The variable I is: " << I << endl; } Note: replacing ‘I’ by ‘Number’ in the main does not change anything.

Slide 50 Pass by Reference: Example 1 * To show how the function affects a variable which is used as a parameter: #include using namespace std; void Increment(int& Number){ Number = Number + 1; cout << "The parameter Number: " << Number << endl; } void main(){ int I = 10; Increment(I); // parameter is a variable cout << "The variable I is: " << I << endl; }

Slide 51 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass by reference. * Efficiency for large objects! * Reference (address) of parameter is passed to the function, instead of its value. * If the function changes the parameter value, the changes will be reflected in the program calling it.

Slide 52 l &, … l int& x, double& y, char& z l The notation T& means a reference to T Specify the passing of a parameter by reference: T& Very ‘interesting’ notation we will continue to see it later on … ‘reference’ does not exist in C, ramification of low-level pointer. int y=10; int& x = y; // x and y refer to the same int l A reference is an alternative name for an object.

Slide 53 l Pass by value: formal parameters and arguments are different variables. ideal desirable behavior (but not efficient some times) l Pass by reference: they are the same variables, but different names! should carefully handled! Pass by value vs. by reference

Slide 54 Example 2 * It is possible to use both pass by reference and pass by value parameters in the same function.

Slide 55 // Print the sum and average of two numbers // Input: two numbers x & y // Output: sum - the sum of x & y // average - the average of x & y #include using namespace std; void SumAve (double, double, double&, double&); void main ( ) { double x, y, sum, mean; cout << "Enter two numbers: "; cin >> x >> y; SumAve (x, y, sum, mean); cout << "The sum is " << sum << endl; cout << "The average is " << mean << endl; } void SumAve(double no1, double no2, double& sum, double& average) { sum = no1 + no2; average = sum / 2; }

Slide 56 * Data areas after call to SumAve:

Slide 57 Example 3: sort 3 integers Input: three numbers First, Second, and Third Output: three numbers in order! Sort 3 numbers, F, S, and T Sort 2 numbers, F,S Sort 2 numbers, S,T Sort 2 numbers, F,S

Slide 58 Input: three numbers First, Second, and Third Output: three numbers in order! Sort F, S, and T Sort F,S Sort S,T Sort F,S if (first > second) swap (first, second);

Slide 59 // Compare and sort three integers #include using namespace std; void swap (int&, int&); void main ( ) { int first, second, third; // input integers // Read in first, second and third. cout << "Enter three integers: "; cin >> first >> second >> third; if (first > second) swap (first, second); if (second > third) swap (second, third); if (first > second) swap (first, second); cout << "The sorted integers are " << first << ", " << second << ", " << third << endl; }

Slide 60 // Function for swapping two integers void swap (int& x, int& y) { int temp; temp = x; x = y; y = temp; }

Slide 61 #include using namespace std; void sort (int&, int&); Void swap (int&, int&); void main ( ) { int first, second, third; // input integers // Read in first, second and third. cout << "Enter three integers: "; cin >> first >> second >> third; sort(first,second); sort(second,third); sort(first,third); cout << "The sorted integers are " << first << ", " << second << ", " << third << endl; } Also possible … void sort(int& x, int& y) { if(x>y) swap(x,y); } void swap (int& x, int& y) { … }

Slide 62 Summary int max(int x, int y) { int m; if (x>y) m=x; else m=y; return m; } void max(int x, int y, int& m) { if (x>y) m=x; else m=y; } void minmax(int x, int y, int& min, int& max) { if (x>y) {min=y; max=x;} else (min=x; max=y;} } int xx,yy,mm; // OK with m, x, and y cin >> xx >> yy; mm=max(xx,yy); // functional programming style int xx,yy,mm; cin >> xx >> yy; max(xx,yy,mm); int xx,yy,mmin,mmax; cin >> xx >> yy; minmax(xx,yy,mmin,mmax); int main()

Slide 63 Example 4: programme tracing // Pass-by-reference versus pass-by-value example #include using namespace std; void One (int a, int b, int& c) { int d; a = 10; b = 11; c = 12; d = 13; cout << "The values of a, b, c, and d in One: "; cout << a << " " << b << " " << c << " " << d << endl; } void Two (int a, int b, int& d) { int c = 0; cout << "The values of a, b, c, and d in Two: "; cout << a << " " << b << " " << c << " " << d << endl; }

Slide 64 void main () { int a = 1, b = 2, c = 3, d = 4; One(a, b, c); cout << "The values of a, b, c, and d after One: "; cout << a << " " << b << " " << c << " " << d << endl; Two(a, b, d); cout << "The values of a, b, c, and d after Two: "; cout << a << " " << b << " " << c << " " << d << endl; }