# Using functions in C++ - DVD Info ![main1.png](images/main1.png) ![main2.png](images/main2.png) ![main3.png](images/main3.png) A good way to organize and structure computer programs is dividing them into smaller parts using functions. Each function carries out a specific task of the problem that we are solving. You've seen that all programs written in C++ must contain the `main` function where the program begins. You've probably already used functions such as `pow`, `sin`, `cos`, or `sqrt` from the `cmath` library. Since in almost all of the upcoming lab experiences you will continue using pre-defined functions, you need to understand how to work with them. In future exercises, you will learn how to design and validate functions. In this laboratory experience, you will search and display information contained in a DVD data base to practice declaring simple functions and calling pre-defined functions. ##Objectives: 1. Identify the parts of a function: return type, name, list of parameters, and body. 2. Call pre-defined functions by passing arguments by value ("pass by value"), and by reference ("pass by reference"). 3. Implement a simple function that utilizes parameters by reference. ##Pre-Lab: Before you get to the laboratory you should have: 1. Reviewed the following concepts: a. the basic elements of a function definition in C++ b. how to call functions in C++ c. the difference between parameters that are passed by value and by reference d. how to return the result of a function. 2. Studied the concepts and instructions for the laboratory session. 3. Taken the Pre-Lab quiz, available in Moodle. --- --- ## Functions In mathematics, a function $$f$$ is a rule that is used to assign to each element $$x$$ from a set called *domain*, one (and only one) element $$y$$ from a set called *range*. This rule is commonly represented with an equation, $$y=f(x)$$. The variable $$x$$ is the parameter of the function and the variable $$y$$ will contain the result of the function. A function can have more than one parameter, but only one result. For example, a function can have the form $$y=f(x_1,x_2)$$ where there are two parameters, and for each pair $$(a,b)$$ that is used as an argument in the function, the function will only have one value of $$y=f(a,b)$$. The domain of the function tells us the type of value that the parameter should have and the range tells us the value that the returned result will have. Functions in programming languages are similar. A function has a series of instructions that take the assigned values as parameters and performs a certain task. In C++ and other programming languages, functions return only one result, as it happens in mathematics. The only difference is that a *programming* function could possibly not return any value (in this case the function is declared as `void`). If the function returns a value, we use the instruction `return`. As in math, you need to specify the types of values that the function's parameters and result will have; this is done when declaring the function. ### Function header The first sentence of a function is called the *header* and its structure is as follows: `type name(type parameter01, ..., type parameter0n)` For example, ```cpp int example(int var1, float var2, char &var3) ``` would be the header of the function called `example`, which returns an integer value. The function receives as arguments an integer value (and will store a copy in `var1`), a value of type `float` (and will store a copy in `var2`) and the reference to a variable of type `char` that will be stored in the reference variable `var3`. Note that `var3` has a & symbol before the name of the variable. This indicates that `var3` will contain the reference to a character. ### Calling a function The following line assigns the value returned by the function `example` to an integer variable `x`: ```cpp x = example(2, 3.5, unCar); ``` Note that when calling the function we don't include the type of the variables in the arguments as in the function's definition. The third parameter `&var3` is a reference variable. Thus, what is being sent to the third argument when calling the function is a *reference* to the variable `unCar`. Any assignments that are made to the variable `var3` will change the contents of the variable `unCar`. You can also use the function's result without having to store it in a variable. The following line sends the return value of function `example` to the `cout` object, so that it is displayed in the terminal: ```cpp cout << "The result of the function example is:" << example(2, 3.5, unCar);` ``` or use it in an arithmetic expression: ```cpp y = 3 + example(2, 3.5, unCar); ``` ### Overloaded Functions Overloaded functions are functions that have the same name, but different *signatures*. The signature of a function is composed of the name of the function and the types of parameters it receives. The signature does not include the return type. The following function prototypes have the **same signature**: ```cpp int example(int, int) ; void example(int, int) ; string example(int, int) ; ``` Note that each has the same name, `example`, and receives the same amount of parameters of the same type `(int, int)`. The following function prototypes have **different signatures**: ```cpp int example(int) ; int elpmaxe(int) ; ``` Note that even though the functions have the same amount of parameters with the same type `int`, the name of the functions is different. The following function prototypes are overloaded versions of the function `example`: ```cpp int example(int) ; void example(char) ; int example(int, int) ; int example(char, int) ; int example(int, char) ; ``` All of the above functions have the same name, `example`, but different parameters. The first and second functions have the same amount of parameters, but their arguments are of different types. The fourth and fifth functions have arguments of type `char` and `int`, but they have a different order in each case. In that last example, the function `example` is overloaded since there are five functions with different signatures but with the same name. ### Default Values Values by default can be assigned to the parameters of the functions starting from the rightmost parameter. It is not necessary to initialize all of the parameters, but the ones that are initialized should be consecutive: parameters in between two parameters cannot be left uninitialized. This allows calling the function without having to send values in the positions that correspond to the initialized parameters. **Examples of Function Headers and Valid Function Calls:** 1. **Header:** `int example(int var1, float var2, int var3 = 10)` Here `var3` is initialized to 10. **Calls:** a. `example(5, 3.3f, 12)` This function call assigns the value 5 to `var1`, the value 3.3 to `var2`, and the value of 12 to `var3`. b. `example(5, 3.3f)` This function call sends the values for the first two parameters and the value for the last parameter will be the value assigned by default in the header. That is, the values in the variables in the function will be as follows: `var1` will be 5, `var2` will be 3.3, and `var3` will be 10. 2. **Header:** `int example(int var1, float var2 = 5.0f, int var3 = 10)` Here `var2` is initialized to 5 and `var3` to 10. **Calls:** a. `example(5, 3.3f, 12)` This function call assigns the value 5 to `var1`, the value 3.3 to `var2`, and the value 12 to `var3`. b. `example(5, 3.3f)` In this function call only the first two parameters are given values, and the value for the last parameter is the value by default. That is, the value for `var1` within the function will be 5, that of `var2` will be 3.3, and `var3` will be 10. c. `example(5)` In this function call only the first parameter is given a value, and the last two parameters will be assigned values by default. That is, `var1` will be 5, `var2` will be 5.0, and `var3` will be 10. **Example of a Valid Function Header with Invalid Function Calls:** 1. **Header:** `int example(int var1, float var2 = 5.0f, int var3 = 10)` **Invocation:** a. `example(5, , 10)` This function call is **invalid** because it leaves an empty space in the middle argument. b. `example()` This function call is **invalid** because `var1` was not assigned as a default value. A valid call to the function `example` needs at least one argument (the first). **Examples of Invalid Function Headers:** 1. `int example(int var1 = 1, float var2, int var3)` This header is invalid because the default values can only be assigned starting from the rightmost parameter. 2. `int example(int var1 = 1, float var2, int var3 = 10)` This header is invalid because you can't place parameters without values between other parameters with default values. In this case, `var2` doesn't have a default value but `var1` and `var3` do. --- --- ##DVD Movies and the DVD Data Base DVD stands for "digital versatile disk" or "digital video disk", which is an optical disc format for storing digital information invented by Philips, Sony, Toshiba, and Panasonic in 1995. The DVD offers larger storage capacity than compact disks (CD) but has the same dimensions. DVDs can be used to store any kind of digital data but they are mainly famous for their use in the distribution of movies. --- --- !INCLUDE "../../eip-diagnostic/DVD/en/diag-dvd-01.html"
!INCLUDE "../../eip-diagnostic/DVD/en/diag-dvd-03.html"
!INCLUDE "../../eip-diagnostic/DVD/en/diag-dvd-11.html"
!INCLUDE "../../eip-diagnostic/DVD/en/diag-dvd-12.html"

--- --- ## Laboratory Session: In this laboratory session we will be using a database of DVD movies maintained by [http://www.hometheaterinfo.com/dvdlist.htm](http://www.hometheaterinfo.com/dvdlist.htm). This database contains 44MB of information for movies that have been distributed in DVD. Some of the stored information in the database for each DVD is: DVD title, publishing studio, date of publication, type of sound, versions, price, rating, year and genre. The information for each movie is stored in the following format: ``` DVD_Title|Studio|Released|Status|Sound|Versions|Price|Rating|Year|Genre|Aspect|UPC|DVD_ReleaseDate|ID|Timestamp ``` For example, ``` Airplane! (Paramount/ Blu-ray/ Checkpoint)|Paramount||Discontinued|5.1 DTS-HD| LBX, 16:9, BLU-RAY|21.99|PG|1980|Comedy|1.85:1|097361423524|2012-09-11 00:00:00| 230375|2013-01-01 00:00:00 ``` ### Exercise 1 - Familiarize Yourself with the Defined Functions The first step in this laboratory experience is to familiarize yourself with the functions that are already defined in the code. Your tasks require that you imitate what the functions do, for this reason it is important that you understand how to call, declare and define the functions. #### Instructions 1. Load the project `DVDInfo` into `QtCreateor`. There are two ways to do this: * Using the virtual machine: Double click the file `DVDInfo.pro` located in the folder `home/eip/labs/functions-dvdinfo` of your virtual machine. * Downloading the project's folder from `Bitbucket`: Use a terminal and write the command `git clone http://bitbucket.org/eip-uprrp/functions-dvdinfo` to download the folder `functions-dvdinfo` from `Bitbucket`. Double click the file `DVDInfo.pro` located in the folder that you downloaded to your computer. 2. Configure the project. The file `main.cpp` has the function calls that you will use in the next exercises. The declarations and definitions of the functions that will be called can be found in the files `movie.h` and `movie.cpp`. 3. Double click on the file `movie.h` that contains this project's function prototypes. Go to `movie.h` and identify which functions are overloaded and describe why. Study the function prototypes and documentation in `movie.h` so that you understand the task they carry out and the data types they receive and return. For each of the following functions, identify the data types they receive and return: ``` showMovie showMovies getMovieName getMovieByName ``` You can find the function definitions in the file `movie.cpp`. Note that some versions of the function `showMovie` use the object called `fields` of the `QStringList` class. The purpose of this object is to provide easy access to information fields of each movie, using an index between 0 and 14. For example, you may use fields[0] to access a movie’s title, fields[1] to access a movie’s studio, fields[8] to access its year, and so forth. --- !INCLUDE "../../eip-diagnostic/DVD/en/diag-dvd-06.html"
### Exercise 2 - Call and Modify Functions In this exercise you will modify the `main` function and some of the pre-defined functions so that they display only certain movies from the database, display only part of the information, or display the information in a specific format. #### Instructions 1. Notice the following line in the main funcion. ```cpp filemanip file("dvd_csv.txt") ; ``` Its purpose is to associate the object called `file` with the data file `dvd_csv.txt`. When openning a data file in a program it is often necessary to specify the file's **absolute path** to guarantee that the program finds the file regardless of where it is executed. Find out the **absolute path** of `dvd_csv.txt` and substitute it for the current `"dvd_csv.txt"` string. For example, after the change the line might look as follows: ```cpp filemanip file("/home/eip/functions-dvdinfo/dvd_csv.txt") ; ``` Compile and run the program. If you see errors such as `Cannot open dvd_csv.txt`, then the path is incorrect. Correct the path until you get no errors when executing. 1. Perform the following implementations in the `main` function (in the `main.cpp` file): * Add code so that the program displays the movies that have positions from 80 to 100. * Add code so that the program displays only the movies that have “forrest gump” in the title. * Add code so that the program displays only the movie in position 75125 using function composition and the function `showMovie`. * Add code so that the program displays the name and the rating of the movie in position 75125. 1. Modify the `getMovieInfo` function in the file `movie.cpp` so that it receives an additional parameter by reference where the name of the movie will be assigned. Remember that you must also modify the function's prototype in `movie.h`. 1. Add the necessary code to the `main` function so that, using `getMovieInfo`, it displays the name, rating, year and the genre of the movie in position 75125 in one line. Hint: note that the function `getMovieInfo` has parameters that are passed by reference. ### Exercise 3 - Define and Implement Functions The functions whose prototypes are in `movie.h` are implemented in the file `movie.cpp`. In this exercise you will use the files `movie.h`, `movie.cpp`, and `main.cpp` to define and implement additional functions. As you implement these functions, remember to use good programming techniques and document your program. #### Instructions 1. Study the functions that are already implemented in `movie.cpp` so that they may be used as examples for the functions you will create. 2. Implement a function `getMovieStudio` that receives a string with the information of a movie and returns the name of the film's **studio**. Remember to add the function's prototype in the file `movie.h`. Invoke the function `getMovieStudio` in `main()` to display the name and studio of the movie in the position 75125 and demonstrate its functionality. 3. Implement an overloaded function `getMovieInfo` that returns the name of the studio as well as the name, rating, year and genre. Call the function `getMovieInfo` in `main()` to display the name, studio, rating, year and genre of the movie in the position 75125 and demonstrate its functionality. 4. Implement a function `showMovieInLine` that **displays** the information displayed by `showMovie`, but in a single line. The function should have a parameter to receive a string of information of the movie. Call the function `showMovieInLine` in `main()` to display the information for the movie in position 75125 to demonstrate its functionality. 5. Implement a function `showMoviesInLine` that **displays** the same information displayed by `showMovies` (all of the movies within a range of positions) but in a single line per movie. For example, a function call would be: `showMoviesInLine(file, 148995, 149000);`. Call the function `showMoviesInLine` in `main()` to display the information and demonstrate its functionality. --- --- ## Deliverables Use "Deliverables" in Moodle to hand in the files `main.cpp`, `movie.cpp`, and `movie.h` with the function calls, changes, implementations and declarations that you made in Exercises 2 and 3. Remember to use good programming techniques, include the names of the programmers involved, and document your program. --- --- ## References [1] http://mathbits.com/MathBits/CompSci/functions/UserDef.htm [2] http://www.digimad.es/autoria-bluray-dvd-duplicado-cd-video.html [3] http://www.soft32.com/blog/platforms/windows/keep-your-dvd-collection-up-to-date-with-emdb-erics-movie-database/ [4] http://www.hometheaterinfo.com/dvdlist.htm