Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sahar Mosleh California State University San MarcosPage Build-in Functions.

Similar presentations


Presentation on theme: "Sahar Mosleh California State University San MarcosPage Build-in Functions."— Presentation transcript:

1 Sahar Mosleh California State University San MarcosPage Build-in Functions

2 Sahar Mosleh California State University San MarcosPage Functions - A method for allowing a program to be implemented in pieces - A function is a block of code that performs some operations and (possibly) gives back a result -Suppose you were doing something really basic - e. g. opening a file, calculating a square root - Silly to write code for this over and over - Much easier to include it in a library of routines and re- use it whenever you want

3 Sahar Mosleh California State University San MarcosPage Functions -This is what happens whenever you use a #include to make use of a library of routines (a header file) -e.g. when you include fstream, you get access to a routine to open a file -also other routines we haven’t used yet -Someone has written a set of functions, that you can make use of when you include the appropriate header file

4 Sahar Mosleh California State University San MarcosPage Built-In functions -There are many of these built-in functions and correspondingly, many header files -For example, say you want to calculate a square root. That’s in the math header file. #include

5 Sahar Mosleh California State University San MarcosPage Built- In Functions #include using namespace std; int main () { float num, answer; cout << “Enter a value: ”; cin >> num; answer = sqrt(num); cout << “The square root of ” << num << “ is ” << answer << endl; }

6 Sahar Mosleh California State University San MarcosPage Built- In Functions -sqrt is the name of the function -num is the value we want to take the square root of -Like this one, functions require specific information to perform their jobs - Parameters

7 Sahar Mosleh California State University San MarcosPage Supplying Arguments answer = sqrt( 3.7); answer = sqrt(6+2); -When we call a function, we supply specific values (arguments) for the parameters the function requires -They are supplied in brackets when we call the function -more on these terms later -Arguments can be specified directly (i.e. as literals), in variables or constants, or as the result of complex expressions

8 Sahar Mosleh California State University San MarcosPage Supplying Arguments answer = pow(3,7); - If we have to supply several arguments, we separate them by commas - pow (also in math header file) calculates its first argument raised to the power of its second (3 7 ). - The order of the arguments is important – if we reversed them, we’d get 7 3 !

9 Sahar Mosleh California State University San MarcosPage Calling Built- In Functions - What happens when we call a built-in function? - The arguments we supply are evaluated, and passed to the function - The function runs (code we don’t see - from the header file) - The function eventually completes - Often it calculates and returns a result

10 Sahar Mosleh California State University San MarcosPage Returning a Result - When a function returns a result, it will have a specific type – e.g: both pow and sqrt return floats - We have to do something with this result – Store it: answer = sqrt(X); – Print it: cout << sqrt(X); – Pass it on to other calculations: x = 2 + pow(7,14); y = sqrt( pow(2,4));

11 Sahar Mosleh California State University San MarcosPage Output Formatting Functions - In the iomanip header file - Allow us to create more nicely formatted output #include using namespace std; int main () { int x = 4; cout << setw(5) << x << endl; } - setw sets the width (# spaces) the next data item should take up!

12 Sahar Mosleh California State University San MarcosPage Output Formatting Functions cout << setw( 5) << x; - Pads with blanks on left to appropriate length. Here, bbbb4 would be printed (where b = blank) - Only works for the next item (i.e. you have to repeat this if you want the same formatting) - Default for setw is 0 - leaves just enough room for value - What about real numbers (floats)?

13 Sahar Mosleh California State University San MarcosPage Formatting Floats -The way in which floats are formatted depends on your compiler -The text gives a few lines that sets up floating point formatting for whatever you’re using cout.setf(ios::fixed, ios::floatfield); cout.setf( ios::showpoint); -once you’ve done this (just copy in the lines, don’t even worry what they do) you can set the decimal point precision

14 Sahar Mosleh California State University San MarcosPage Formatting Floats setprecision( ) sets the number of decimal places to print #include using namespace std; int main () { cout.setf(ios::fixed, ios::floatfield); cout.setf( ios::showpoint); cout << setprecision(3); float x = 4.7589; cout << setw(7) << x; } Output: bb4.759 (where b= blank)

15 Sahar Mosleh California State University San MarcosPage Output Formatting Function -Note the rounding - the number is rounded off for printing -doesn’t change the value in the variable at all -The width will be increased if necessary to fit the number -Unlike setw, setprecision has lasting effects -once used, all floats will continue to be printed that way until you change it

16 Sahar Mosleh California State University San MarcosPage User- Defined Functions - So, we know how to use functions provided for us by other programmers - There are lots of them, but they obviously don’t cover everything we want - We want to be able to write our own functions!

17 Sahar Mosleh California State University San MarcosPage User Defined Functions -Why?? - So we can re-use them later if we want - So we can divide our programs into pieces - Re-use has obvious advantages – more compact programs, no repeated code, and not having to rewrite code later for similar problems - But why would we want to divide a program into pieces?

18 Sahar Mosleh California State University San MarcosPage Dividing Programs into Pieces -To make the program more manageable -If we have pieces of a program that do individual tasks, we can isolate errors and modifications -Take the square root routine for example… if you had to write it… -You could test it separately from the rest of your program; errors found later are not as likely to be in the square root function! -You could modify the internals of the function without affecting the rest of your program!

19 Sahar Mosleh California State University San MarcosPage Dividing Programs into Pieces -Before we talk about how to create our own functions, we need to talk about dividing programs up -Obviously, we don’t just do it randomly

20 Sahar Mosleh California State University San MarcosPage Top-Down Design -A technique for designing programs -Useful without even knowing anything about functions -Helps us to handle the “where do I start?” -Lets us gradually design a program without being overwhelmed by details

21 Sahar Mosleh California State University San MarcosPage Top-Down Design -Begin with a high-level statement of the problem -Clearly this is not something that you could implement directly - but it does give you a general statement of what you’re trying to do -Now break this into smaller problems

22 Sahar Mosleh California State University San MarcosPage Top-Down Design - Asking the user is pretty much implementable at this point (a concrete step) - Change prices is still pretty vague (abstract step), so we can break that one down too... Update prices for big sale Ask user for % off Change prices Change prices

23 Sahar Mosleh California State University San MarcosPage - Now everything is concrete - we’re done! - Each box is a module, The entire diagram is a structure chart and shows how modules are related - Each module should be functionally cohesive - it should do one, well-defined thing Change prices Open price filesRead a priceDiscount pricePrint new price Top-Down Design

24 Sahar Mosleh California State University San MarcosPage Top-Down Design -You should always do a design for each program -Gives you a handle on where to start -Ensures you know what you’re doing before you start programming! -You should only start implementing after your design is complete!

25 Sahar Mosleh California State University San MarcosPage User-Defined Functions The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh

26 Sahar Mosleh California State University San MarcosPage User- Defined Functions - Functions are a facility provided by C++ to implement the modules in your design - Allows each module to be physically separate from others and re-used as necessary - We’ve already been using user-defined functions. Every C++ program starts with one function called main(); we add others as necessary

27 Sahar Mosleh California State University San MarcosPage User- Defined Functions - Are similar to built-in functions - They have a name, parameters, can return a result, and are called exactly like built in functions - So we know a lot about them already! - Let’s look at a simple example

28 Sahar Mosleh California State University San MarcosPage Simple Function Example void printabar() { cout << “*****************************”; } - The function header contains information like the name, what data it needs to do its job, etc. More on this in a moment Function Header - Information about the function Function Body - statements that perform the function’s task

29 Sahar Mosleh California State University San MarcosPage Simple Function Example void printabar() { cout << “*****************************”; } - Notice how similar this is to the programs we’ve been writing so far? - That’s because main() is a function! - All C++ programs have a function called main, and that is where execution of the program begins

30 Sahar Mosleh California State University San MarcosPage Simple Function Example void printabar() { cout << “*****************************”; } - How do we make use of this function? - We call it, just like a built-in function - use it’s name and brackets: printabar();

31 Sahar Mosleh California State University San MarcosPage Simple Function Example void printabar() { cout << “*****************************”; } - We know what one looks like, we know how to call it, but where do we put them? - We already have one function in our program - main() - We can put them in any order, but main() usually comes first - so we can get an immediate overview of what the program does before looking at the details - There’s a problem with this though…..

32 Sahar Mosleh California State University San MarcosPage Declaration Before Use - Many languages, including both C++ and Pascal, have a rule that forces you to declare anything you want to use before you use it - That’s why we have to declare variables! - This is a problem in functions. Suppose I want to call my printabar function inside main. If main comes first, how will the compiler know what I’m talking about!?!

33 Sahar Mosleh California State University San MarcosPage We could put printabar (and other functions we want to use) first; then, however, we’d have to hunt through all these details before we got down to main and found out what the program actually does! We try to use printabar here But because its down here, the compiler hasn’t even seen it yet we will get an error every time we use it void main () { printabar(); } //--------------------------- void printabar() { } Declaration Before Use

34 Sahar Mosleh California State University San MarcosPage Prototypes - There is a solution to this problem - a special statement that lets the compiler know what upcoming functions are going to look like before actually implementing them - A Prototype - Since most of the information about a function is in its header, it will look pretty much like the function header itself - There will be a few differences we will see later when we look at more complicated functions - Lets look at the whole thing using a prototype

35 Sahar Mosleh California State University San MarcosPage Prototypes Example #include using namespace std; void printabar (); void main () { // this is the main program pretend there’s // lots of other statements here printabar(); } // end main //-------------------------------------------- void printabar() { // printbar code goes here } // end printbar This prototype tells C++ everything it needs to figure out if you are calling printabar properly or not

36 Sahar Mosleh California State University San MarcosPage Prototypes Example #include using namespace std; void printabar (); void main () { // this is the main program // pretend there’s lots of other statements here printabar(); } // end main void printabar() { // printabar code goes here // pretend there’s some statements here } // end printabar All the functions we use can now immediately follow main, provided each has a prototype that appears before main

37 Sahar Mosleh California State University San MarcosPage More Complex Functions - We now know a fair bit about functions: - What one looks like - Where they appear in the program - how to call them - But our functions don’t do much yet. Lets look at some more complex situations

38 Sahar Mosleh California State University San MarcosPage Parameters - Our printabar function is so trivial, it doesn’t really do much of anything - Like most built-in functions, our own functions will generally require some information to work with - Say we wanted to use printabar to print bars for a line graph -bars aren’t always the same length - When we wanted to use the function, we’d have to provide some data indicating the number of characters to print

39 Sahar Mosleh California State University San MarcosPage Parameters - We indicate in our function that data will be provided when we call the function by declaring parameters - A parameter acts like a variable (details later), and holds the value we give to the function when we call it - You will also see Parameters called Formal Parameters - because they’re defined formally as part of the function

40 Sahar Mosleh California State University San MarcosPage Using Parameters void printabar (int numchars) { int count= 1; while (count <= numchars) { // loop to print 1 char at a time cout << ‘*’; count++; //incrementing the counter } cout << endl; } - Here’s our function with a parameter added - We define its type and give it a name - We can have a list of parameters separated by commas (like declaring a bunch of variables)

41 Sahar Mosleh California State University San MarcosPage Using Parameters void printabar (int numchars) { int count= 1; while (count <= numchars) { // loop to print 1 char @ a time cout << ‘* ’; count++; // remember to increment counter! } cout << endl; } - Note that we don’t give the parameter a value!!! The value will be supplied when we call the function

42 Sahar Mosleh California State University San MarcosPage Arguments void main () { printabar(6); printabar(3); } - Now we need to specify a value between the brackets when we call printabar - This is an argument - data we supply to work with at the time we call the function - Arguments are also called Actual Parameters - Arguments are matched to parameters by ORDER (we’ll talk about it later)

43 Sahar Mosleh California State University San MarcosPage Parameters and Prototypes void printabar(int); - Here you see the appropriate prototype for the function with parameters - Note its now a little different from the function header - Prototypes give C++ the info it needs to tell if you are correctly calling the function - It needs the name, needs to know if there are parameters and what type they are, but doesn’t care about their names - The names are optional; you only really need to list the types of the parameters in order

44 Sahar Mosleh California State University San MarcosPage Call by Value Call by Reference

45 Sahar Mosleh California State University San MarcosPage Returning Values - The examples we’ve seen so far are very different from most built-in functions we’ve used - They just do something - they don’t give any answer back! - Most built- in functions calculate something and return it (sqrt, pow, etc.) - How can we do this?

46 Sahar Mosleh California State University San MarcosPage Void and Non-Void Functions - Every function has a type - Part of the header, tells C++ what type of value the function will give back when we call it - The first word of the header defines the type of the function - The functions we’ve used so far don’t return values - The type void is used to indicate this - If you want to return a value, simply supply the type you want instead of void

47 Sahar Mosleh California State University San MarcosPage Non- Void Functions int mypower (int x, int y) { // raise x to power y (y >= 0) using a count- controlled loop int count= 1; // loop counter int answer= 1; // holds the answer while (count <= y) { // loop to print 1 char @ a time answer = answer * x; count++; } // end while return answer; } // send answer back to caller Note >1 parameter Causes function to terminate and send back value we’ve specified

48 Sahar Mosleh California State University San MarcosPage Calling Non-Void Functions - When we call this function, just like most built-in functions, we need to do something with the result: - Store it: answer = mypower(x,y); - Print it: cout << mypower(2,3); - Pass it on to other calculations: x = 2 + mypower(7,14); y= sqrt( mypower(2,4)); - Remember that the order of arguments matters!!!

49 Sahar Mosleh California State University San MarcosPage Prototypes for Non-Void Functions - For a prototype of this function, we need to add the type information (just as we needed to use void in earlier examples) int mypower( int x, int y); - Remember that you can actually put the parameter names if you want, but they’re irrelevant

50 Sahar Mosleh California State University San MarcosPage More on Return - Return may also be useful in terminating a function prematurely - You can use it anywhere in the function, and you can use it without a value in a void function to simply cause the function to terminate early - Example: while (1) { cin >> x; if (x < 0) return; else // lots of other code }

51 Sahar Mosleh California State University San MarcosPage More on Return - Is also commonly used in the main function - we usually give the main function a type of int, and return some integer indicating whether the program ran correctly - e. g. return 0 for no error, higher numbers for more severe problems int main () { // whatever main does return 0; } - The text uses this; feel free to use it if you want

52 Sahar Mosleh California State University San MarcosPage So far… - We have functions which implement the modules in our program designs - These functions can accept arguments, which provide data for the function to work with - These functions can also return results if we want them to

53 Sahar Mosleh California State University San MarcosPage Returning more than one result - But suppose we want to return more than one result? - Suppose you wanted an interactive program that would calculate volume for the user. - You repeatedly want to obtain length, width, and height - This might be something you want a separate function for - But how? A function can only return one result... but there are ways around this

54 Sahar Mosleh California State University San MarcosPage Parameter Types - The answer lies in a new type of parameter we haven’t seen yet - Recall that the parameters we have used so far act like variables: - They get created when a function is called - A value is passed into them from the caller - They cease to exist when the function returns - So given that, what do you think would happen in the following example:

55 Sahar Mosleh California State University San MarcosPage Example int strange( int); int main() { int arg = 7; cout << strange(arg); cout << endl << arg ; } int strange( int y) { y = 6; return 0; } We print the result of calling strange, which is 0 (the value returned by strange) But what’s happening here? We print arg, which is 7 Or is it? When we call strange, we change it’s parameter to 6….

56 Sahar Mosleh California State University San MarcosPage Altering Parameter Values - According to what we know happens with parameters, 7 should be printed - That’s because - - the parameter y is created when the function runs - the argument is copied into it (the 7)... - and even though we change y to 6, y itself is destroyed when the function returns - So our original argument, arg (with the value 7) is never touched and can’t be!

57 Sahar Mosleh California State University San MarcosPage Parameter Types - But it doesn’t always have to be this way! - We are making use of only one of two types of parameters allowed by C++ - These are called Value Parameters, because as the name implies, the argument values are copied into the parameter, and the original argument can never be changed - There’s a second type that DOES allow argument values to be changed

58 Sahar Mosleh California State University San MarcosPage Reference Parameters - This second type is called a Reference Parameter - For the moment, just assume that when you declare one, you’re allowed to actually make changes to the argument being passed - We can and do use this to return values from functions - Since we can have as many parameters as we want, we can return as many values as we’d like in them by altering the parameters!

59 Sahar Mosleh California State University San MarcosPage Reference Parameters - Very easy to declare - just put an ampersand (&) at the end of the data type of the parameter name: int& x - So, when writing functions, just ask yourself if you want the original argument to be changeable, and if you do, add the ampersand! - Let’s see our strange example with reference parameters...

60 Sahar Mosleh California State University San MarcosPage Example int strange( int&); int main() { int arg = 7; cout << strange(arg); cout << endl << arg ; } int strange( int& y) { y = 6; return 0; } The parameter y is now a Reference Parameter - this means that whatever we pass to y can be altered!

61 Sahar Mosleh California State University San MarcosPage Example int strange( int&); int main() { int arg = 7; cout << strange(arg); cout << endl << arg ; } int strange(int& y) { y = 6; return 0; } y will be set to the value 6... So arg is passed to strange y will be 7 as before

62 Sahar Mosleh California State University San MarcosPage Example int strange( int&); int main() { int arg = 7; cout << strange( arg); cout << endl << arg ; } int strange( int& y) { y = 6; int answer = y*2; return answer; } - Obviously, we have to be careful with these! arg, after the call to strange, will also have the value 6!

63 Sahar Mosleh California State University San MarcosPage Mechanics of Reference Parameters - It’s important to understand what’s going on here - First of all, reference parameters don’t behave any differently than value parameters - They’re still created when the function is called - They still get an argument from outside - They’re still destroyed when the function returns

64 Sahar Mosleh California State University San MarcosPage Mechanics of Reference Parameters - Then how can they work the way they do? - Do they copy the parameter back into the argument when the function returns? - No, they don’t do that either - Their behavior has everything to do with WHAT is actually being passed

65 Sahar Mosleh California State University San MarcosPage Mechanics of Reference Parameters - In a value parameter, the actual value of the argument is copied into the parameter - The 7 is copied over and then strange runs …. arg y 7 7

66 Sahar Mosleh California State University San MarcosPage Mechanics of Reference Parameters - In a reference parameter, the value is not passed; the memory address of the argument is! - In fact, ‘y’ becomes an alias name for variable ‘arg’. Any change in ‘y’ makes the same change in ‘arg’ …. arg y 7

67 Sahar Mosleh California State University San MarcosPage Back to our Example - More importantly, considering the full example: int strange( int& ); int main() { int arg = 7; cout << strange( arg); cout << endl << arg ; } int strange( int& y) { y = 6; return 0; } So when strange returns,arg has the value 6, and that is what is printed!

68 Sahar Mosleh California State University San MarcosPage Something to Remember - You never have to worry about the address business yourself! - You don’t care in this example what the address of arg happens to be; the compiler handles all this for you - This is an example of what’s properly called a pointer, something we’ll study in advanced C++ course

69 Sahar Mosleh California State University San MarcosPage Returning Multiple Values - We can use reference parameters to return as many values as we want - In our original example, we wanted to read in length, width and height - It’s easy now!

70 Sahar Mosleh California State University San MarcosPage Returning Multiple Values int main() { float l, w, h; getvalues(l, w, h); cout << “volume is “ << l*w*h; } //------------------------------------------------ void getvalues(float& len, float& wid, float& height) { cout << “enter an integer length: ”; cin >> len; cout << “enter an integer width: ”; cin >> wid; cout << “enter an integer height: ”; cin >> height; }

71 Sahar Mosleh California State University San MarcosPage Returning Multiple Values - getvalues doesn’t return anything... - instead, it has three reference parameters - when we input values, we change these, and change the variables the caller supplies! - Getvalues takes l, w, h as arguments, and because each of its parameters is a reference parameter, it actually modifies l, w, and h, effectively allowing the function to give back three values

72 Sahar Mosleh California State University San MarcosPage Returning Multiple Values - But suppose I did this! int main() { int l, w, h; getvalues( 6, 2, 3); // other code after this } - It doesn’t make sense does it? How can the function change a 6, or a 2??? It can only change what’s stored in a variable!

73 Sahar Mosleh California State University San MarcosPage Big Restriction - We can only pass variables to reference parameters! - As in the last example, this should make sense, because they’re the only things that can be modified - i.e. the only things that have an address that can be referred to - There’s one other thing to be aware of

74 Sahar Mosleh California State University San MarcosPage Watch out for Type Coercion! - We’ve seen that C++ tries to convert types to allow the statements we make - e. g. converting characters to integers using the collating sequence if we assign a character to an integer - Odd things happen if we do this in a reference parameter - since the types don’t match, it can’t use them directly - instead, it creates a second variable, coerces, and uses that - Unexpected result can happen - so make the types to be the same when using call by reference

75 Sahar Mosleh California State University San MarcosPage Use Reference Parameters Carefully! - It’s easy to make changes to arguments you don’t intend - Such changes can be hard to trace back! - Don’t use reference parameters unless you want values passed back - There are always exceptions, but treat this as a rule for now!


Download ppt "Sahar Mosleh California State University San MarcosPage Build-in Functions."

Similar presentations


Ads by Google