This post is completed by 4 users

  • 1
Add to List
Beginner

In a number, add digits until it becomes a single digit

Write a program to add the digits of the given number until the number becomes a single digit number.

Example:

Input: 256, Output: 4
256 -> 13 -> 4

Input: 15, Output: 6
15 -> 6

Input: 82, Output: 1
82 -> 10 -> 1

Input: 242239, Output: 4
242239 -> 22 -> 4

Approach:

In this article we are using recursion which can be easily modified to an iterative solution. I start with the given input number and find the sum of all its digits and make a recursive call with the input equal to the sum. Base cases are:

  • When the input number is less than 10 then return the number.

Complete Code:


Output:

Input: 256, Output: 4
Input: 15, Output: 6
Input: 82, Output: 1
Input: 242239, Output: 4



Also Read: