0% found this document useful (0 votes)
54 views

Recursion: Data Structures & Algorithms

Recursion is a programming technique where a function calls itself to solve a problem. It works by solving a smaller version of the same problem first. For example, calculating the factorial of a number n (written as n!) can be done recursively by defining it as n! = n * (n-1)! and having the function call itself with decreasing values of n until it reaches the base case of 0!. This recursive solution is contrasted with an iterative solution using a for loop.

Uploaded by

Aamir2686
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

Recursion: Data Structures & Algorithms

Recursion is a programming technique where a function calls itself to solve a problem. It works by solving a smaller version of the same problem first. For example, calculating the factorial of a number n (written as n!) can be done recursively by defining it as n! = n * (n-1)! and having the function call itself with decreasing values of n until it reaches the base case of 0!. This recursive solution is contrasted with an iterative solution using a for loop.

Uploaded by

Aamir2686
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Recursion

Data Structures & Algorithms

Introduction

A programming technique in which a

function calls itself. One of the most effective techniques in programming.

What is recursion?

Sometimes, the best way to solve a problem


is by solving a smaller version of the exact same problem first Recursion is a technique that solves a problem by solving a smaller problem of the same type

When you turn this into a program, you end up with functions that call themselves (recursive functions)
int function(int x) { int y; if(x==0) return 1; else { y = 2 * function(x-1); return y+1; } }

Problems defined recursively

There are many problems whose solution


can be defined recursively Example: n factorial
n!= 1 (n-1)!*n 1 1*2*3**(n-1)*n if n = 0 if n > 0 if n = 0 if n > 0 (recursive solution)

n!=

(closed form solution)

Coding the factorial function

Recursive implementation
int Factorial(int n) { if (n==0) // base case return 1; else return n * Factorial(n-1); }

Iterative implementation
int Factorial(int n) { int fact = 1;

Coding the factorial function (cont.)

for(int count = 2; count <= n; count++) fact = fact * count; return fact; }

You might also like