0
0
DSA Typescriptprogramming~15 mins

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

Choose your learning style9 modes available
Recursion Base Case and Recursive Case
📖 Scenario: Imagine you have a stack of plates, and you want to count how many plates are in the stack by taking one plate off at a time until none are left.
🎯 Goal: You will build a simple recursive function in TypeScript that counts down from a number to zero using recursion. This will teach you how to set a base case and a recursive case.
📋 What You'll Learn
Create a variable called startNumber with the value 5.
Create a recursive function called countDown that takes a number parameter called num.
In countDown, write a base case that stops recursion when num is zero or less.
In the recursive case, print the current num and call countDown with num - 1.
Call countDown with startNumber.
Print each number on its own line.
💡 Why This Matters
🌍 Real World
Recursion is used in many places like searching files in folders, solving puzzles, and processing nested data.
💼 Career
Understanding recursion helps in writing clean code for problems that repeat themselves, which is common in software development and technical interviews.
Progress0 / 4 steps
1
Create the starting number
Create a variable called startNumber and set it to 5.
DSA Typescript
Hint

Use const startNumber = 5; to create the variable.

2
Define the recursive function
Create a function called countDown that takes a parameter num of type number.
DSA Typescript
Hint

Use function countDown(num: number): void { } to define the function.

3
Add base case and recursive case
Inside countDown, write a base case that returns when num is less than or equal to zero. Otherwise, print num and call countDown with num - 1.
DSA Typescript
Hint

Use if (num <= 0) { return; } for the base case. Then print num and call countDown(num - 1).

4
Call the function and print output
Call countDown with startNumber to start the countdown.
DSA Typescript
Hint

Use countDown(startNumber); to start the countdown.