C++ Tutorial #13 – Recursive & Inline Functions


Yes, we are going to work more on functions! Don’t worry, this one will be really easy. In this tutorial, we will learn how to use Recursive Functions and Inline Functions. We will write a program for each of these examples. Fire up your favorite IDE and lets get started.




Recursive Functions are functions that call themselves, causing it to go back in a loop. Think of it as a For Loop or a While Loop, but a function instead. Lets write a program that uses this type function that multiples every number by nine, starting with one that we choose, all the way down to zero!




Your program should look something like this:


15 x 9 = 135
14 x 9 = 126
13 x 9 = 117
12 x 9 = 108
11 x 9 = 99
10 x 9 = 90
9 x 9 = 81
8 x 9 = 72
7 x 9 = 63
6 x 9 = 54
5 x 9 = 45
4 x 9 = 36
3 x 9 = 27
2 x 9 = 18
1 x 9 = 9
0 x 9 = 0



Lets take a look at our function. Remember, it’s a void function so we don’t have to return anything. On line 5, we named our function MutiplesOfNine an we placed int number for our parameter. Inside of our function we created an if statement with number >= 0 for our condition, meaning that our if statement won’t run if int number is less than zeroOn line 9, we used cout to print out the equations. On line 10, we called the function with number-1 for the parameter. This function will keep looping until int number is less than zero.




If you look at the main function, we use the function and set the value for our parameter.







Inline Functions are similar to regular functions. The difference is that inline functions make the program more efficient by inserting the code where the function is called, instead of calling the function. Only use this when your function is small, otherwise, you’ll make your program less efficient.




The program should just print “25” on the screen like this:




Take a look at our inline function. It’s just a simple function. It takes a number, and squares it.



In our main function, we create two integers x & y. We set y = 5, and square it with our function. We set x to equal to square(y), and print it with cout.



So nothing really new here, but I wanted to show you the example to avoid confusion. Inline Functions are the same as writing a regular function. Just remember that its more efficient to use inline functions on small functions, and regular functions on larger functions.


We are not completely finished with functions. There are a few more tutorials coming up, but I just wanted to cover these two simple functions before we move on. Practice up on each of the function tutorials, and understand how each one of them works. I will be posting new tutorials soon.


About Justin

Computer programmer and owner of kauergames.com.
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.