Recursion: Functions that call themselves

In this example, the function half receives a number. If the number is > 0, we print the number and then call half passing number/2. Notice that this is an integer. If we try this with a double, we will get what amounts to an endless loop.

half
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Half problem: recursive
#include <iostream>
using namespace std;
void half(int n) {
   if(n>0)  {
       cout<<n<<endl;
       half(n/2);
   } 
} //half

int main() {
   int num;
   cout<<"Enter a number:";
   cin>>num;
   half(num);
   system("pause");
   return 0;
} //main
CODE

When the program runs, multiple instances of the function are active at once.

half running

Notice that this would be easier and more efficient to just use a loop. Try writing this program with a loop.

NEXT: Catching Errors