Functions and recursion: Difference between revisions
wikademia>Shatner New page: This lesson will have to do with using functions and recursion to improve readability and efficiency of your code. This lesson assumes you have a general grasp of C++ syntax. Other than th... |
wikademia>Eme m moved Beta:Functions and recursion to Functions and recursion over redirect |
||
| (17 intermediate revisions by 10 users not shown) | |||
| Line 1: | Line 1: | ||
This lesson will have to do with using functions and recursion to improve readability and efficiency of your code. This lesson assumes you have a general grasp of C++ syntax. Other than that, I will explain everything as well as I can. | This lesson will have to do with using functions and recursion to improve readability and efficiency of your code. This lesson assumes you have a general grasp of C++ syntax. Other than that, I will explain everything as well as I can. | ||
{{?}} | |||
==Functions== | ==Functions== | ||
Simply put | Simply put a function is a segment of code that is isolated from the main code segment. A function is ''called'' from a section of code. When the function's code has been executed, it ''returns'' to the calling code. The general form of a function is: | ||
:{| | :{| | ||
| Line 26: | Line 26: | ||
===The <tt>main<tt> Function=== | ===The <tt>main<tt> Function=== | ||
The <tt>main<tt> function is a special function. Every C++ program must contain a function named "main". It serves as the entry point for the program. The computer will start running the code | The <tt>main<tt> function is a special function. Every C++ program must contain a function named "main". It serves as the entry point for the program. The computer will start running the code from the beginning of the main function. | ||
There are two main types of <tt>main<tt> functions; one with and one without parameters. Below are examples of both: | There are two main types of <tt>main<tt> functions; one with and one without parameters. Below are examples of both: | ||
<pre> | <pre> | ||
| Line 104: | Line 104: | ||
} | } | ||
</pre> | </pre> | ||
There are many things to note in this example. First is the use of the two prototypes that precede the <tt>main<tt> function. They allow <tt>main<tt> to use <tt>fctn1<tt> and <tt>fctn2<tt> even though they aren't | There are many things to note in this example. First is the use of the two prototypes that precede the <tt>main<tt> function. They allow <tt>main<tt> to use <tt>fctn1<tt> and <tt>fctn2<tt> even though they aren't defined until after <tt>main<tt>. | ||
Next, notice that to call <tt>fctn1<tt> all we had to do was enter <tt>fctn1();<tt>. Since it doesn't require any arguments and it has a <tt>void<tt> return value, this is very simple. For <tt>fctn2<tt> however, we see that it not only requires two arguments, but also returns an integer as well. To pass data to a function, you simply list the data in the order it is called for by the function definition. To catch the returned data, we use the assignment operator '=' and assign the returned value to a variable <tt>sum<tt>. | Next, notice that to call <tt>fctn1<tt> all we had to do was enter <tt>fctn1();<tt>. Since it doesn't require any arguments and it has a <tt>void<tt> return value, this is very simple. For <tt>fctn2<tt> however, we see that it not only requires two arguments, but also returns an integer as well. To pass data to a function, you simply list the data in the order it is called for by the function definition. To catch the returned data, we use the assignment operator '=' and assign the returned value to a variable <tt>sum<tt>. | ||
| Line 111: | Line 111: | ||
===Parameters=== | ===Parameters=== | ||
Parameters are how data is passed between functions through the call of the function. Above we learned that you list the data you want to pass to a function in the call between the <tt>( )<tt>. The order of the list is determined by the function definition. The first parameter in the list will be assigned to the variable | Parameters are how data is passed between functions through the call of the function. Above we learned that you list the data you want to pass to a function in the call between the <tt>( )<tt>. The order of the list is determined by the function definition. The first parameter in the list will be assigned to the variable listed first in the function definition. Also, in most cases, you must have the correct number and type of data being passed to the function or you will receive an error when you try to compile your program. | ||
For example: | For example: | ||
| Line 126: | Line 126: | ||
This would pass the contents of the variable <tt>num1<tt> to <tt>arg1<tt> in the function. Then the integer value '12' would be passed to <tt>arg2<tt>. | This would pass the contents of the variable <tt>num1<tt> to <tt>arg1<tt> in the function. Then the integer value '12' would be passed to <tt>arg2<tt>. | ||
====Passing Methods==== | |||
By default, values are passed to a function through a method called '''''pass by value'''''. This means that the value of the variable is passed, not the variable itself. This would be like giving a person a copy of your driver's license. They can read all of your information and they can change whatever they want on their copy, but the original is not altered in any way. | By default, values are passed to a function through a method called '''''pass by value'''''. This means that the value of the variable is passed, not the variable itself. This would be like giving a person a copy of your driver's license. They can read all of your information and they can change whatever they want on their copy, but the original is not altered in any way. | ||
| Line 138: | Line 139: | ||
!# values altered !! Return !! Pass by value !! Pass by reference | !# values altered !! Return !! Pass by value !! Pass by reference | ||
|- | |- | ||
| 0 || N || Y || N | | 0 || N || Y || N | ||
|- | |- | ||
| 1 || Y || Y || N | | 1 || Y || Y || N | ||
|- | |- | ||
| 2+ || N || N || Y | | 2+ || N || N || Y | ||
|} | |} | ||
You can mix between the use of pass by value and pass by reference from parameter to parameter, but it is not good programming practice to mix the use of pass by reference and returning. | You can mix between the use of pass by value and pass by reference from parameter to parameter, but it is not good programming practice to mix the use of pass by reference and returning. | ||
====Default Parameters==== | |||
It's possible to assign default values to parameters that are omitted from the function call. The default values are usually defined in the function prototype like this example: | |||
<pre> | |||
int addTwoInts(int = 4, int = 5); | |||
</pre> | |||
In this case, if the parameters aren't provided, they will be assigned 4 and 5 respectively. So, for example, if you had the call | |||
<pre> | |||
temp = addTwoInts(); | |||
temp = addTwoInts(33); | |||
</pre> | |||
Neither of these calls would raise an error. In the first one, both values would be set to their defaults. In the second example, the first argument would be passed 33 while the second argument would still be defaulted to 5. You cannot default the second one without defaulting the first one as well. | |||
===Scope=== | ===Scope=== | ||
Scope refers to the level of access an object has. A function can access only global variables and those that are passed to it through arguments. Also, any | Scope refers to the level of access an object has. A function can access only global variables and those that are passed to it through arguments. Also, any variables declared inside a function are only available to that function. | ||
For example, an integer declared in <tt>main<tt> will not be available to any other function unless it is passed as an argument. Vis versa, an integer declared in a function will not be available to the <tt>main<tt> function. | For example, an integer declared in <tt>main<tt> will not be available to any other function unless it is passed as an argument. Vis versa, an integer declared in a function will not be available to the <tt>main<tt> function. | ||
{| | ==Recursion== | ||
''Recursion'' is a method of function calling in which a function calls itself during execution. Let's start by showing an example and then discussing it. | |||
- | <pre> | ||
int factorial(int n) | |||
{ | |||
if(n == 1 || n == 0) | |||
{ | |||
return 1; | |||
} | |||
else | |||
{ | |||
return n*factorial(n-1); | |||
} | |||
} | |||
</pre> | |||
This is a classic application of recursion. This function calculates the factorial of a number. As you probably know the factorial of n, written n!, is the product of every number from 1 to n. So we can say that 4! = 4×3×2×1. Let's step through what happens in our function when we call <tt>num = factorial(4)<tt>. | |||
*<tt>factorial(4)<tt> is called | |||
:*Since n=4, we take the <tt>else<tt> path. We return 4×<tt>factorial(n-1)<tt> | |||
:*<tt>factorial(3)<tt> is called | |||
::*Since n=3, we take the <tt>else<tt> path. We return 3×<tt>factorial(n-1)<tt> | |||
::*<tt>factorial(2)<tt> is called | |||
:::*Since n=2, we take the <tt>else<tt> path. We return 2×<tt>factorial(n-1)<tt> | |||
:::*<tt>factorial(1)<tt> is called | |||
::::*Since n=1, we take the first path and finally return 1 to the previous function | |||
:::*<tt>factorial(1)<tt> returns 1 so <tt>factorial(2)<tt> can return 2×1...2 | |||
::*<tt>factorial(2)<tt> returns 2 so <tt>factorial(3)<tt> can return 3×2...6 | |||
:*<tt>factorial(3)<tt> returns 6 so <tt>factorial(4)<tt> can return 4×6...24 | |||
Many times, a recursive solution to a problem is very easy to program. The drawback of using recursion is that there is a lot of overhead. Every time a function is called, it is placed in memory. Since you don't exit the <tt>factorial<tt> function until n reaches 1, n functions will reside in memory. This isn't a problem for the simple factorial(4), but other functions can lead to serious memory requirements. | |||
==Where To Go Next== | |||
{{Cpp_Lessons}} | |||
[[Category:Programming]] | |||
[[Category:C++]] | |||