
- Functional Programming Tutorial
- Home
- Introduction
- Functions Overview
- Function Types
- Call By Value
- Call By Reference
- Function Overloading
- Function Overriding
- Recursion
- Higher Order Functions
- Data Types
- Polymorphism
- Strings
- Lists
- Tuple
- Records
- Lambda Calculus
- Lazy Evaluation
- File I/O Operations
- Functional Programming Resources
- Quick Guide
- Useful Resources
- Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Functional Programming - Recursion
A function that calls itself is known as a recursive function and this technique is known as recursion. A recursion instruction continues until another instruction prevents it.
Recursion in C++
The following example shows how recursion works in C++, which is an object-oriented programming language −
#include <stdio.h> long int fact(int n); int main() { int n; printf("Enter a positive integer: "); scanf("%d", &n); printf("Factorial of %d = %ld", n, fact(n)); return 0; } long int fact(int n) { if (n >= 1) return n*fact(n-1); else return 1; }
It will produce the following output
Enter a positive integer: 5 Factorial of 5 = 120
Recursion in Python
The following example shows how recursion works in Python, which is a functional programming language −
def fact(n): if n == 1: return n else: return n* fact (n-1) # accepts input from user num = int(input("Enter a number: ")) # check whether number is positive or not if num < 0: print("Sorry, factorial does not exist for negative numbers") else: print("The factorial of " + str(num) + " is " + str(fact(num)))
It will produce the following output −
Enter a number: 6 The factorial of 6 is 720
Advertisements