I am trying to learn about recursives and found this code on the internet. It works, but am not sure why. Could some one explain to me why this works. I have posted comments by the function to explain what I do not understand.

#include <iostream>
using namespace std;

void printDisplay(int);

int main() 
{

   printDisplay(5);
   printDisplay(900);
   printDisplay(1234);

   return 0;
}

void printDisplay(int n)   //I understand the n is coming from main
{
   cout << n % 10;  // this takes the number and gives the remainder when divided by 10.
   if (n < 10) {  //if statement understand this.
	cout << endl; //why are you cout an empty line?
	return; }//What are we returning.
   printDisplay(n / 10);//why are we dividing the number by 10?
}

You cout an empty line just means "do a carriage return". That's because when n is less than 10, you have finished, so you should go to the next line.

What the code does it take a number n, print out the last digit, then remove the last digit (divide by 10), and repeat.

So for example, if you have a number 768, and you call the function, this is what happens:
First, it prints out 8, on the line cout << n%10;
Then it divides 768 by 10, to get 76 (they are integers) and repeats.
Now it prints out 76%10 = 6. Then it repeats.
Prints out 7%10 = 7. Then since 7 < 10, it prints out a carriage return, so that now you are on the next line.

the function is constantly reducing the number untill it is less than 10.
lets say the number is 100. the function would print 0 for the first time. then you check to see if it is greater than 10. since 100 is greater than 10 we will call the print function but this time we will dived 100 by 10 and pass that into the function.

so now we have 10. we do the same thing and again it displays 0. 10 is not less than 10 so we dived 10 by 10 and call the function again.

now we have 1. 1 % 10 is 1 so it displays 1. now 1 is less than 10 so we print out a blank line and exit the function via the return statement. since this is a void function we don't need to return anything.

So this function prints out a number backwards using recursion. if you still are unclear about any of this let me know. also if you are using a newer compiler i would suggest setting a break point in the function and stepping through it with the debugger to watch it work.

[EDIT]
Xorlium beat me to it. ;)

Thanks, makes complete sense

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.