Recursion

Recursion Functions

When a function calls itself is known as recursion. Recursion works like loop but sometimes it makes more sense to use recursion than loop. You can convert any loop to recursion.

A recursive function calls itself. Imagine a process would iterate indefinitely if not stopped by some condition! Such a process is known as infinite iteration. The condition that is applied in any recursive function is known as base condition. A base condition is must in every recursive function otherwise it will continue to execute like an infinite loop.

Overview of how recursive function works

1. Recursive function is called by some external code.

2. If the base condition is met then the program gives meaningful output and exits.

3. Otherwise, function does some required processing and then calls itself to continue recursion.

Here is an example of recursive function used to calculate factorial.

Example :

def fact(n):
	if n == 0:
		return 1
	else:
		return n * fact (n-1)
	print (fact (0))
	print (fact (5))

Output:

1

120

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz