March 23, 2021

Sum of all digit of number using python

 Question :

Find sum of all digit of number :-

this problem is solved by two method  :-

1st is without recursion method and 

2nd is using recursion method 

let's start ,

Without recursion method 

step 1 :

make a function with name sumofDigit(num) : and pass the argument which is entered from the user 

def sumofDigit(num):


step 2 :

we use while loop here for checking if num is grater then 0 is show in the code below :-

add=0

while num>0:

if the condition is True then we move to the next step


step 3 :

this step is totally on logic as shown below : -

add  =  add  + num%10

num = num//10

print(add)                #to print the result


step 4 :

in the step you come out from the function and call the function  as shown below : -

num=int (input("enter the number : "));            #take input through user 

sumofDigit(num)                     #function call 


COMPLETE SOURCE CODE 



1st method of without using recursion 

#sum of 4 digit number without recursion


num=int (input("Enter the number : "))

add=0

while num>0:

     add=add+num%10

     num=num//10


print(add)


2nd Method using recursion 

#sum of 4 digit using recurssion

def sdig(num):

    if num==0:

        return 0

    return ((num%10) + sdig(num//10))



num=int (input("Enter the number : "))

print(f"sum of digit of {num} is {sdig(num)}")


No comments:

Post a Comment

find the cube of the range given digits. || codeAj

Find the cube of the range given Digits. Source Code r= int ( input ( "enter the range of digit : " )) def number_conter (n): ...