Thursday , September 21 2017
Home / Python / Python program to calculate digit sum

Python program to calculate digit sum

Python program to calculate sum of the digits of a number here is a : This Source code for digit sum is calculated by getting the remainder and dividing each number by 10 in every iteration.

The digit sum of a given integer number is the sum of all its individual digits.

Example for digit sum:-

Digit Sum Program in Java

Digit Sum Iteration 1 :

  • 1894%10 = 4
  • 1894/10= 189
  • value of S = 0+ 4

Digit Sum Iteration 2 :

  • 189%10=9
  • 189/10= 18
  • Value of S=4+9

Digit Sum Iteration 3 :

  • 18%10=8
  • 18/10=1
  • Value of S=13+8

Digit Sum Iteration 4 :

  • 1%10=1
  • 1/10=0
  • Value of S= 21+1

Digit Sum Iteration 5 :

  • Terminates because of false Condition of loop.

You can also see a simple program on how to get sum of two number in C language.

  • i = input("nEnter any number to find the Digit Sum: ")  #get the input for calculate digit sum.
    temp = i = int(i) #String change to int
    rem = s = 0 #Initialization of remainder and sum.
    while (  temp > 0) :   #calculation of digit sum.
        rem = temp % 10
        temp = temp/10
        s = s +rem
    print ("nDigit Sum of  %d is %d" % (i,s))

    Output:

    Enter any number to find the Digit Sum: 14353
    Digit Sum of 14353 is 16.

    Enter any number to find the Digit Sum: 123456789
    Digit Sum of 123456789 is 45.

  • n = int(input("Enter a number: "))
    
    if n < 0:
       print("Enter a positive number")
    else:
       s = 0
       while(n > 0):     # use while loop to iterate untill zero
           s += n
           n -= 1
       print("The Digit sum is",s)

    Output:-

    Enter a number: 1694913782453266
    The Digit sum is 76

    Enter a number: 9876541
    The Digit sum is 40

Leave a Reply

Your email address will not be published. Required fields are marked *