
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursive Sum of All Digits in a Number using JavaScript
Let’s say, we are required to create a function that takes in a number and finds the sum of its digits recursively until the sum is a one-digit number.
For example −
findSum(12345) = 1+2+3+4+5 = 15 = 1+5 = 6
So, the output should be 6.
Let’s write the code for this function findSum() −
Example
// using recursion const findSum = (num) => { if(num < 10){ return num; } const lastDigit = num % 10; const remainingNum = Math.floor(num / 10); return findSum(lastDigit + findSum(remainingNum)); } console.log(findSum(2568));
We check if the number is less than 10, it’s already minified and we should return it and from the function otherwise we should return the call to the function that recursively takes the last digit from the number adds to it until it becomes less than 10.
Output
So, the output for this code will be −
3
Advertisements