Functions and recursion: Difference between revisions
wikademia>Steaxauce m →Scope |
wikademia>Eme m moved Beta:Functions and recursion to Functions and recursion over redirect |
||
| (5 intermediate revisions by 2 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 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: | 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 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>. | ||