 # Recursion in Programming – tririd.com

Recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. Such problems can generally be solved by iteration, but this needs to identify and index the smaller instances at programming time.

Most computer programming languages support recursion by allowing a function to call itself from within its own code.

To solve a problem recursively means that you have to first redefine the problem in terms of a smaller sub problem of the same type as the original problem.

Example,

If we want to sum of 1 to 10 no without loop then we can use recursion like following:

int sum(int n)

{

If (n == 1)

return 1;

}

else

{

return n + sum(n-1);

}

void main()

{

int no;

//input value of no at runtime….

ans = sum(no);

//display ans here…

}

}

What is use of Recursion?

Recursion is made for solving problems that can be broken down into smaller, repetitive problems. It is especially good for working on things that have many possible branches and are too complex for an iterative approach. One good example of this would be searching through a file system.

In the above summation problem, to sum-up n integers we have to know how to sum-up n-1 integers. Next, you have to figure out how the solution to smaller sub problems will give you a solution to the problem as a whole. This step is often called as a recursive leap of faith. Before using a recursive call, you must be convinced that the recursive call will do what it is supposed to do. You do not need to think how recursive calls works, just assume that it returns the correct result.