0
0
DSA Cprogramming~30 mins

Recursion Base Case and Recursive Case in DSA C - Build from Scratch

Choose your learning style9 modes available
Recursion Base Case and Recursive Case
📖 Scenario: Imagine you want to find the factorial of a number. Factorial means multiplying the number by all smaller numbers down to 1. For example, 4 factorial is 4 x 3 x 2 x 1 = 24.
🎯 Goal: You will write a recursive function in C that calculates the factorial of a number using a base case and a recursive case.
📋 What You'll Learn
Create a function called factorial that takes an integer n as input.
Use a base case where if n is 1, the function returns 1.
Use a recursive case where the function returns n multiplied by factorial(n - 1).
Call the factorial function with the value 5 and print the result.
💡 Why This Matters
🌍 Real World
Recursion is used in many places like calculating factorials, navigating file systems, and solving puzzles.
💼 Career
Understanding recursion helps in solving problems that require breaking down tasks into smaller similar tasks, common in software development and algorithm design.
Progress0 / 4 steps
1
Create the factorial function with base case
Write a function called factorial that takes an integer n and returns 1 if n is 1.
DSA C
Hint

The base case stops the recursion. If n is 1, return 1.

2
Add the recursive case to factorial function
Inside the factorial function, add a recursive case that returns n * factorial(n - 1) when n is not 1.
DSA C
Hint

The recursive case calls factorial again with n - 1 and multiplies the result by n.

3
Call factorial function with 5
In the main function, call factorial with the value 5 and store the result in an integer variable called result.
DSA C
Hint

Use int result = factorial(5); to call the function and save the answer.

4
Print the factorial result
Add a printf statement in main to print the value of result with the message: "Factorial of 5 is: %d\n".
DSA C
Hint

Use printf("Factorial of 5 is: %d\n", result); to show the answer.