Recursion in Functions
Recursion in programming refers to a function calling itself in order to solve a problem. A recursive function solves a problem by solving smaller instances of the same problem.
#include <iostream>;
using namespace std;
// Recursive function to calculate factorial
int factorial(int n)
{
if (n == 0) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
int main()
{
int result = factorial(5);
cout<< "The factorial is " << result;
return 0;
}
public class Factorials {
// Function to calculate factorials
public static int factorials(int n) {
// Base case: if n is 0, factorial is 1
if (n == 0) {
return 1;
}
// Recursive case: calculate factorial by multiplying n with the factorial of (n-1)
else {
return n * factorials(n - 1);
}
}
// Main method
public static void main(String[] args) {
// Calculate factorial of 5
int result = factorials(5);
// Print the result
System.out.println("The factorial is " + result);
}
}
# Function to calculate factorials
def factorials(n):
# Base case: if n is 0, factorial is 1
if n == 0:
return 1
# Recursive case: calculate factorial by multiplying n with the factorial of (n-1)
else:
return n * factorials(n - 1)
# Main function
def main():
# Calculate factorial of 5
result = factorials(5)
# Print the result
print("The factorial is", result)
# Call the main function
main()
function factorials(n) {
// Base case: if n is 0
// factorial is 1
if (n === 0) {
return 1;
}
// Recursive case: calculate factorial by the multiplying n with the factorial of (n-1)
else {
return n * factorials(n - 1);
}
}
// Main function
function main() {
// Calculate factorial of the 5
let result = factorials(5);
// Print the result
console.log("The factorial is " + result);
}
main();
Output
The factorial is 120
Functions in Programming
Functions in programming are modular units of code designed to perform specific tasks. They encapsulate a set of instructions, allowing for code reuse and organization. In this article, we will discuss about basics of function, its importance different types of functions, etc.
Table of Content
- What are Functions in Programming?
- Importance of Functions in Programming
- Functions Declaration and Definition
- Calling a Functions in Programming
- Parameters and Return Values
- Built-in Functions vs. User-Defined Functions
- Recursion in Functions
- Tips for Functions in Programming
- Conclusion
Contact Us