Unformatted text preview:

Day 10: User-defined functionsArguments and parametersReasons for writing a functionReasons (cont.)TerminologyDay 11: More examples of functionsCall by valueExample of call by valueCommentsCall by valueMore examplesHW2 solutionDay 12: ArraysDeclarationDeclarationInitialization at declarationArraysIndices in arraysExampleExample: Minimum of arrayPassing arrays to functionsDay 13Void return typeBubble sort (HW3)Minimum as functionDay 14: Black boxFunction prototypesIntroducing a functionIntroducing a functionHeader filesConst variables and parametersDay 15Scope of variablesGlobal variablesFunction examplesDay 16: ExamplesMore examplesEven more examplesDay 17Call by referenceCall by referenceCall by reference (cont.)Call by reference exampleAnother exampleDay 18Character arraysExample programDay 10: User-defined functionsHW2, Challenge 2: area of a polygonexample: factorial functionz remember to ‘throw exception’ on errorfunction namefunction callArguments and parametersmust pass information into the functionargument: value before it is in functionz foo = factorial(5); // 5 is the argumentparameter: value once inside functionz int factorial (int n) { … }z n is the formal parameterformal parameters are variables of the functionz yes, they are declared in an unusual placez they can change during the functionReasons for writing a functionencapsulate code that needs to be repeated several timesz write once, call several timesz don’t repeat yourselfz a miniature programz can save commonly used functions in a library and use across lots of programs (header file, separate object code to be linked)Reasons (cont.)separate a logically distinct chunk of codez clean interface: z know what this chunk of code depends on (its parameters)z cannot mess with other parts of codez can move variable declarations local to the function into the function definitionz can debug and test separatelyz cleans up code, even if you only call the function oncez don’t have a function with > 50 statements (say)Terminology3 terms for breaking a program into functionsz divide and conquerz stepwise refinementz top-down designprogram politely: don’t eat your task in one biteDay 11: More examples of functionsarea (rectangle, circle)Call by valueHow are values passed to a function?In C++, the default passing mechanism is call by value.call by value: initialize ith formal parameter with value of ith argumenta series of assignment statements as you hand off control to functionno communication between calling function and called function after this handoff, until returnExample of call by valueint doubleIt (int i) {i = 2*i;return i;}void main() {int a=1,b;b = doubleIt(a);cout << “a = “ << a << “ b = “ << b << endl;}Commentsthings to notice from above example:z can change value of formal parameter inside the body of function: it’s just a special variablez changes to formal parameter have no effect on associated argument!z this is the essence of call by value: any connection between the argument and formal parameter is cut after value is copied overwarning: Savitch is misleading (at best) on this issue of call by valueCall by valuethere is another calling mechanism, call by reference, but there is no need for this for a whileJava doesn’t even allow call by reference parameters (for primitive types)we will talk about it laterMore examplescall by value examples: deg2rad, rad2deg, fabs, distance between 2 ptsHW2 solutionforeshadowing: distance using arraysHW2 solutiondist as functionsave (x1,y1)store (xold,yold) and (xnew,ynew): active edgebe careful with Boolean conditionDay 12: Arraysoften need to collect elements togethere.g., vector, grades in this class, integers you are sortingarray = cluster of values accessible by indexmathematics: a_0, a_1, a_2, …C++: a[0], a[1], a[2], …lowest index is 0Declarationint a[50]; // 50 student grades// equivalent to 50 integer variables, but with// same name, distinguishable by indexfor (int i=0; i<50; i++) {cout << “Grade for student “ << i << “:”;cin >> a[i];}// Note: a[49] is the last element of the arrayDeclarationtype name[size];int a[50];Initialization at declarationfloat pt[3] = {-3.0, 20.0, 0.0};float pt[] = {-3.0, 20.0, 0.0};float pt[3] = {-3.0, 20.0};float pt[3]; pt[0]=-3.; pt[1]=20.; pt[2]=0.;all of these have identical semanticsArraysmemory allocationin declaration, number in [] is sizein all later uses, number in [] is indexint a[50]; // finea[50] = 0; // logical error: one past endhow does it store address of beginning of array? in the array nameIndices in arraysindex = offset from beginning of arraystart at index 0like we count centuries:z 1600’s = 17thcenturyz a[16] = 17thelement of arraya[i] refers to the array element at offseta[(5+2*i)/3] = 2;Exampleadd 5 elementsz result = a + b + c + d + e;z result = a[0] + a[1] + a[2] + a[3] + a[4]; orz result = 0;for (int i=0; i<5; i++) result += a[i];now think about adding 1000 elementsExample: Minimum of arrayint data[100];<fill in array>int minval = data[0]; // minimum valueint mini=0; // index of minimum valuefor (int i=1; i<100; i++)if (data[i] < minval) {minval = data[i]; mini=i;}Passing arrays to functionsstill call by valuethe value is the pointer to the beginning of the arrayrecall that the name of an array is a symbol for the pointer to the beginning of the arraychanges to array inside function ARE reflected outside of function (why?)e.g., distance between 2 pointsDay 13allow selection sort on HW3 for 90% credit (again use functions)Void return typea function may not naturally return something: void return typevoid helloWorld() { … }Bubble sort (HW3)example in Knuthn passes left to right over input (n bubble passes)z in each pass, consider all neighbours (i,i+1)z swap them if out of orderexample: 5,2,6,1,3; after 1 pass, 2 passes, …refinements: can stop passes earlyith pass bubbles the ith largest element up to its correct locationMinimum as functionminimum as functionversion where you only store index of minimumDay 14: Black boxfunction as ‘black box’z cannot see inside to view contentsz only see input and outputz thus, cannot rely on internal behaviourz only need to know function prototypeallows implementation of function to change later, without affecting function callscan hand off implementation to another team member: only have to agree on interfacealso called information hiding or procedural abstractionFunction prototypesanother way of introducing a function before


View Full Document

UAB CS 201 - User-defined functions

Documents in this Course
Load more
Download User-defined functions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view User-defined functions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view User-defined functions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?