TECH GUIDE BLOG

Tech Guide Programming Tutorial Tips Tricks

Recursion in Programming

Posted by Admin On August - 9 - 2009

What exactly recursion is in programming? Recursion is a function that calls the function itself. Thus, in the body of function there is a command that called the function itself. If you use it well, it can solve a problem much more simple and easy. Recursion itself uses a large amount of memory, so be aware not to use it if not necessary. To make a good recursion, of course the functions must have a condition that makes it stop, so the function will not do an infinite looping. I’ve tried it without a stop condition, I compiled it and wow, NOD32 detected my .exe as a virus, I don’t know if the NOD32 made a false detection or not, but if it’s true, then it’s not too difficult to make a virus, eh? Just a little mistake in a program that you’ve made for good reasons and you’ve made a virus.

This code below is an example of how recursion function is working.

#include <stdio.h>
#include <conio.h>

void letter(char alp)
{
	if (alp <= 'e')
	{
		printf("%c ", alp);
		letter(alp + 1);
	}
}

void main()
{
	char temp = 'a';
	letter(temp);
	getch();
}

We call the function and it will print letters from ‘a’ to ‘e’. From the start of the program at void main, we fill a variable with char type called temp with ‘a’. We then call the letter function with temp as parameter, into the letter function, the variable named alp will be filled with ‘a’. Here’s the stop condition, if alp is lower or equal than ‘e’, the function will continue its routine, the function will print what is in the alp variable. After the function printed what is in the alp variable, it call itself with alp + 1 as the parameter, thus this looks like the function is going down 1 level. This routine ended when alp variable is filled with ‘f’, it will go up to the upper level and so on until back to the top level.

It’s a little confusing for me, so I made a ‘level’ for this explanation. Every time a function (you can say function1) called another function (function2), I decided to make a function2 as level 2 function, below the level 1 function (function1). So when letter function with temp as parameter called a letter function with alp + 1 parameter, I set in my mind the letter function with temp parameter as level 1 function and letter function with alp + 1 parameter as level 2, letter function with (alp + 1) + 1 parameter as level 3 function respectively. I hope this tutorial can help.

Popularity: 7% [?]

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • MySpace
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Twitter

One Response to “Recursion in Programming”

  1. Solar Panel says:

    Whoa, good read. I just found your blog and I’m already a fan. :)

Leave a Reply