Write a program to recursively sum the individual digits to obtain a single digit using VB.net

Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 1422
Let's say, we have a number as N=123456789

If we sum them the result will be 1+2+3+4+5+6+7+8+9 =45 . If we further sum them it will be 4+5 = 9, which is a single digit.

How can we do so? The below is the program that will help us

Imports System

Namespace ConsoleApplication1
Class Program
Private Shared Sub Main(args As String())
End Sub

Public Shared Function FindSingleDigit(N As Integer) As Integer
Dim sum = 0
While N <> 0
sum = sum + (N Mod 10)
N = N/ 10
End While
Return If(sum >= 10, FindSingleDigit(sum), sum)
End Function
End Class
End Namespace

Let us understand the program first

While N <> 0
sum = sum + (N Mod 10)
N = N / 10
End While

The loop continues till the value of "N" becomes zero and it gives the total sum of the individual digits. Then it comes out of the loop. Next we perform a checking if the sum obtained is greater than or equals to 10 which is a two digit. In that case , then program makes a recursive call. If it is a single digit, then that value gets return.

Let us analyze the program with out example.

Pass 1: sum = 45
Pass 2: sum = 9

Comments or Responses

Login to post response