Sunday, December 16, 2012

Recursive

I've heard a lot of people saying that recursive is difficult to understand. I think, it's true. But, if every lesson is too easy, why would people build school, college, and university.

Let's take a look at recursive. 

 
It's like calling our own name.
We can call our friends, our teachers, our family, but don't forget that it's also possible to call our self. Try to imagine this situation. If you get it, let's continue. 
In programming, we can make a main function. Inside this, we can call another function or method. But we can also call a method within the method itself. Can you see the similarity? I'll give an example in C language. 
The left picture shows that the main()  can call the Calling() method. You could imagine that main() is a person, and Calling() is main()'s friend. 
The right picture shows that, even inside the main(), we could call the main() itself. This is when main() got lonely and call itself. This kind of situation is called recursive

It isn't that difficult right. Let's talk about the output
The left source code, produces a single line output saying "Hello someone" while the right one produces the same line but written infinitive. It won't stop. Why is this happening? 
The left one works this way.
  1. main() calls Calling()
  2. Calling() does it's task which is write "Hello someone"
  3. After Calling() finished it's task, main()'s first task is done. It continues to system("pause")
  4. End of program
The right one works this way.

  1. main() calls Calling()
  2. Calling() does it's task which is write "Hello someone"
  3. After Calling() finished it's task, main()'s first task is done. It continues to main().
  4. when main() is called, it does step number 1 until 3 again. 
The process in the right source code will never end. Why? Because main() doesn't know when to stop. Then how could we make it stop? Figure it out yourself or read the next chapter. :)
next post

No comments:

Post a Comment