[Skip Navigation] [CSUSB] / [CNS] / [Comp Sci & Eng Dept] / [R J Botting] / [CSci201] / 11
[Text Version] [Syllabus] [Schedule] [Glossary] [Labs] [Projects] [Resources] [Grading] [Contact] [Search ]
Notes: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] <11> [12] [13] [14] [15] [16] [17] [18] [19] [20]
Podcasts: [01] [02] [03] [04] [05] [06] [07] [08] [09] [10] [11] [12]
Labs: [01] [02] [03] [04] [05] [06] [07] [09] [10]
Tue Feb 12 18:44:22 PST 2008

Contents


    pages 122-143 Advanced Functions

      Reading

        Podcast: [ 11.mp3 ] is a reading of the Introduction below.

        Introduction

        This part of CompSci201 is all about functions. It covers Skansholm from section 4.2 to the end of chapter 4. First the text introduces the C++ way of coding procedure. Procedures are named pieces of code that you can write once and then use many times. They differ from typed functions in that they don't return a value and so they should not be used inside an expression. They are effectively a new home-made command that you have added to the C++ language. In this chapter the book develops a library of input/output procedures as examples. Page 120 shows how to use peek and get. Then comes the 'change_to' function for a character array. I have put the equivalent (and simpler) code for a vector on my web site (below). Similarly the code on page is a good example of the techniques but is written as a single statement if we use strings instead of a character array. However the code on page 122 for formatted output looks as it might be useful in several projects. You might like to input it, test it, and store it in your home directory.

        Section 4.3 explains the ideas of scope and visibility -- where variables have particular meanings in you program. You will need to remember the rules if you want to avoid some surprising compile errors in the future. It also discusses a very nice feature of C++. You can have many functions with the same name as long as the have different types of parameters. The compiler picks the function that matches the call that have written.

        Section 4.4 shows you how to split a function declaration from it definition. This can make programs easier to read. The real value of splitting the declaration form the body of a function is that you can now spread the code for a program into many files. This is described in section 4.5 but I think we can skip this in CS201. It is covered in CS202. However I have put a correction to the code on page 131 on the website.

        Section 4.6 is vital. This introduces a new kind of parameter called a reference parameter. Other parameters are evaluated when the functions is called. Reference parameters are not copied. The call must provide a variable, and the code in the body of the function works with the variable you provide, not the one in the code. As a result any changes made to the variable actually change it. Now, we often need to do this... the book has some examples. There are many more. Notice the syntax. The presence of an ampersand (&) character makes the difference between a program that works and one that fails. I will be testing to see if you have learned this.

        Section 4.6 describes a simple and useful feature of C++. You can provide a value for a parameter or argument in the declaration. If the call omits the parameters at the end then the compile provides values to fill out the call. A simple feature that you might not need in CS201.

        The last section, section 4.8, gets into a very elegant, powerful, but somehow nerve racking feature of all modern (post 1960) programming languages. It is very simple: since you can call a function after it has been declared, you must be able to call it inside the body of the function. In other words the function is defined in terms of itself. Good programmers use this feature called "recursion" and it turns up in job interviews! In this class we will look at some examples and I may put one in a lab for you to play with. They become vital in CSCI202 and onward.

        I have a good page of notes.... please look at those as well as reading the book. See you in class.

        4.2 Functions that do not return a value

        Defining a procedure (AKA void function):
         		void name ( arguments ) { body }
        Using a procedure
         		name ( arguments );
        Effect -- when the call is executed
        1. The arguments are evaluated and passed to the arguments in the function body
        2. The body executes
        3. The computer jumps back to the next statement after the call.

        page 119 -- output a new line

        page 120 -- jump to start of next line of input

        page 120 -- global change character in a text

        This is useful for the old C strings. With the new C++ strings we would just write
         	void (string & s, char c, char cnew)
         	{  s.replace(0,s.size(), c, cnew);
         	}

        page 121 -- inputting chars

        This would be useful in the older C. It still makes a nice example of "look-ahead" with "peek" when reading data. Also notice the careful way that Skansholm tests for i<n-1 before anything else. Another subtle point: the careful addition of a null character at the end of the character array.

        The bad news is that this function will do strange things if the person using it does not pre-allocate n+1 characters to there own array.

        To input a word (any length) safely and simply in C++ use strings:

         		cin >> s;

        page 122 -- formatted output

        You might want to type in and test a copy of this function for your project work.

        4.3 Declaration Scope and Visibility

        page 123 -- multiple uses for variable names

        Very useful -- especially when several people work on one program. Note -- most programming is a team effort.

        My notes [ 10.html#Scope ] are on the web page for the previous class.

        page 125 -- overloaded functions

        A great convenience!

        4.4 Function Declarations

         		type name ( arguments );
         		void name ( arguments );
        You can spit the specification or declaration of a function (how to call it) from the definition/implementation of the function! The declaration tells the compiler what it needs to know about the function for you to be able to call it.

        Recall: you can use a function any time after it is declared. So we can put all the details of how a function does things at the end of file as long we declare it before we use it.

        Indeed we can precompile the complete definition of a function and link it into our program without recompiling it.

        4.5 Division of Programs -- CS202

        How to split up a big program into many small files.

        Use on big projects. Used on all real projects. Used in CS202.

        Lets skip it this quarter!

        But please note the changes to the compiler commands on page 131. On Linux you would write

         		g++ -c main.cpp
         		g++ -c simpleio.cpp
         		g++ -o wordprog main.o simple.o
        This is where Makefiles start to become a very useful tool.

        4.6 Reference Parameters

        Here are my notes on the three kinds of parameter/argument.

        Pass by Value

        The normal argument is an expression that is evaluated before the function is called. The resulting value is the initial value of the variable listed in the function header.
                 type name (...., type argument, ....)
                 void name (...., type argument, ....)

        Pass by Reference

        Some arguments are called by reference. These must be variables not expressions. They are not evaluated. The function is instead given the address of the variables and uses these in place of the symbol in the function header.

        A call by reference is shown in the header by adding an ampersand symbol after the type:

                 type name (...., type & argument, ....)
                 void name (...., type & argument, ....)
        Use this whenever you want a function to change the data owned by the calling program. If only one argument is changed think about making the function into one that returns the new value instead.

        Pass by Constant Reference.

        Call by Reference is the most efficient way to share complex data with a function. But, it also permits the function to change the arguments. This can make it difficult to find out what is going on in a program. It is therefore possible to indicate that an argument is called by reference but is safe from being changed:
                 void name (...., const type & argument, ....)
                 type name (...., const type & argument, ....)
        Use this whenever the type is an array, vector, or any other type of object -- it the most efficient way to share complex data between the calling code and the subprogram. And the compiler will prevent the function from changing the shared data.

        4.7 Parameters with default values

        A new option in C++. Useful but not essential.

        4.8 Recursive Functions

        Recursive functions scare a lot of people -- but they work as well as any programming technique. First be sure you have a problem that is itself recursive. Second make sure you have a set of base values. Third make sure the the recursive calls move the arguments closer to the base values.

        You may have heard of fractals -- these are all recursive functions.

        page 140 -- classic factorial

        page 143 -- the classic reverse function

        Recursive functions are a topic of great interest in CSCI202 but we can probably take them lightly in CS201.

      . . . . . . . . . ( end of section Reading) <<Contents | End>>

      Project 4 is due.

      [ projects.html#P4 ]

      Glossary and Jargon

    1. argument::programming=a value or variable that is passed to a function when the function is called.
    2. parameter::mathematics=argument.
    3. reference::=the address of a variable.
    4. procedure::=A subprogram that does not return a value, in C++ called a void function.
    5. recursive::=if you don't understand what this is please look up recursion on this page.
    6. recursion::=the process of defining a function in terms of itself, see recursive.

      Questions

        I read everything but I'm getting lost -- is this OK

        No, it is not OK. But it does happen sometimes. Take a deep breath and step back a little.... Spend a little more time in the labs and a little less time reading perhaps?

        What was the point of exercise 3.1

        Just to show that you could do it. It is harder than it looks. And you should add to the problem an output statement to prove that the program worked.

        How does a search know what number to search for

        You have to have a parameter or variable that contains the target number. I usually call it target. If you need to get both the target and the numbers into the computer from the user in this course you will either need to read in the number of numbers first and then the target (or targets). An alternative is o read in a single target first and then read in all the numbers until CTRL/D.

        How do you campare to strings

        If you have two strings, like this:
         		string s1....
         		string s2....
        Then you can use the same operations as you do with ints:
      1. s1 == s2
      2. s1 != s2
      3. s1 <= s2 (lexical order)
      4. s1 >= s2 (lexical order)
      5. s1 > s2 (lexical order)
      6. s1 < s2 (lexical order)

        If the data are null-terminated character arrays (texts) then you need to use:

         		strcmp( "abc", "abd")
        which returns the difference of the first two characters that a not equal. It give 0 if the two arrays are equal.

        How are functions used

        Functions are used when they are included in a program and then called.

        You should use them to contain common calculations and tasks.

        They let a sigle statement of simple expression stand for a complex computation.

        What functions help you round numbers in different ways

        You get standard rounding when ever you assign a double to an int variable. This converts the double to the nearest int.

        The cmath library has two functions that convert doubles to integers. They are named ceil and floor. The function ceil returns the smallest integer that is not less than the value of the parameter -- the ceiling above the number. The function floor returns the largestest integer that is not greater than the value of the parameter.

        Should we put a return statement at the end of a voif function

        Not really. The compiler will do it for you anyway.

        What makes a function and advanced function

        It has one or more of the following features:
        1. reference parameters
        2. default values for parameters
        3. recursion
        4. etc.

        How do we avoid overcomplicated functions

        Divide them into simpler and small functions.

        How to avoid overloaded functions

        Don't!

        So can we make our own library of functions

        Yes. Put them in a file called mylib.cpp for example and
         	#include "mylib.cpp"
        (Notice the double quotes -- they tell the compiler to start looking for the include library in the same directory as the include statement. )

        If you have a lot of useful function you might conside precompiling them and having a header file "mylib.h". But this is upto you.

        What if two overloaded functions have the same number of parameters?

        The compiler looks at the types of the parameters and picks the function that fits each call. The compiler will complain at great length if there is no such parameter set, or if there is more than one.

        Explain the declaration scope of an Entity

        It is the places in the program text where using the entity referes to a particular declaration.

        What is a recursive function

        Any function whose definition include (directly or indirectly) calling it self.

        What is a reference parameter

        A reference parameter as a "&" (ampersand) character in the its description. It means that each function call will provide a variable. The variable provide in each call will replace the parameter in all computations. This is the best way to communicate several values back to a caling program.

        What is the division of programs in section 4.5

        This is for CS202 and large projects. You split the problem into files and put them in diferent files. You use "#include" to share function declaration. You use a Makefile to make sure that each file is compiled before it used.... there is no such parameter set, or if there is more than one.

        Explain the declaration scope of an Entity

        It is the places in the program text where using the entity referes to a particular declaration.

        What is a recursive function

        Any function whose definition include (directly or indirectly) calling it self.

        What is a reference parameter

        A reference parameter as a "&" (ampersand) character in the its description. It means that each function call will provide a variable. The variable provide in each call will replace the parameter in all computations. This is the best way to communicate several values back to a caling program.

        What is the division of programs in section 4.5

        This is for CS202 and large projects. You split the problem into files and put them in diferent files. You use "#include" to share function declaration. You use a Makefile to make sure that each file is compiled before it used....

        Explain the exercise in the last class

        [ funfun.cpp ] is a test to see if you understand how functions work. Workout what the program does and then download and run it to see if you are right.

        Can we hand in a prject late

        Once you put off a deadline the whole schedule slips.

        The first time you hand in a project I expect it to be somewhere between a total mess and working program. I grade it gently and give you hints on what to do. Then you try a second time -- having got some expert advice ( if needed ).

      . . . . . . . . . ( end of section Questions) <<Contents | End>>

      Exercise Done in Class

      [ 11ex.cpp ] (dowload and play with).

      Quiz 5 -- on simple functions and Project 4

      Lab 06 -- on functions

    Abreviations

  1. Gnu::="Gnu's Not Unix", a long running open source project that supplies a very popular C++ compiler.
  2. KDE::="Kommon Desktop Environment".
  3. OOP::="Object-Oriented Programming", Current paradigm for programming.
  4. SP::="Structured Programming", Previous paradigm for programming.
  5. TBA::="To Be Announced", something I should do.
  6. TBD::="To Be Done", something you have to do.
  7. UML::="Unified Modeling Language", [ 15.html ] (class notes on the UML and OOP).

End