0
0
DSA Cprogramming~30 mins

Factorial Using Recursion in DSA C - Build from Scratch

Choose your learning style9 modes available
Factorial Using Recursion
📖 Scenario: Imagine you want to calculate the factorial of a number, which is the product of all positive integers up to that number. For example, factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.Using recursion, a function can call itself to solve smaller parts of the problem until it reaches the simplest case.
🎯 Goal: You will build a C program that calculates the factorial of a given number using a recursive function.
📋 What You'll Learn
Create a recursive function called factorial that takes an integer n and returns the factorial of n.
Use a base case in the recursion where factorial of 0 is 1.
Call the factorial function with the number 5 and store the result.
Print the result in the format: Factorial of 5 is 120.
💡 Why This Matters
🌍 Real World
Calculating factorial is useful in mathematics, statistics, and computer science problems like permutations and combinations.
💼 Career
Understanding recursion is fundamental for many programming tasks and technical interviews.
Progress0 / 4 steps
1
Create the main function and declare the number
Write a main function and declare an integer variable called number with the value 5.
DSA C
Hint

The main function is the starting point of a C program. Declare int number = 5; inside it.

2
Write the recursive factorial function
Write a recursive function called factorial that takes an integer n and returns an integer. Use the base case: if n == 0, return 1. Otherwise, return n * factorial(n - 1).
DSA C
Hint

The function calls itself with n - 1 until it reaches 0, then returns 1.

3
Call the factorial function and store the result
Inside the main function, call factorial(number) and store the result in an integer variable called result.
DSA C
Hint

Store the factorial of number in result by calling factorial(number).

4
Print the factorial result
Add a printf statement inside main to print: Factorial of 5 is 120 using the variables number and result.
DSA C
Hint

Use printf("Factorial of %d is %d\n", number, result); to print the output.