Program to Print Sum of all Odd Numbers present in a larger number in Python

Program to Print Sum of all Odd Numbers present in a larger number in Python

Sum of all odd numbers

Sum of all odd numbers in a given number can be found by separating each digit from the number and checking whether the number is odd or not , if odd then  add that number if even ignore that. We can also find this by taking input as string , read the algorithm to understand

  • Sample input: 8734835
  • Sample output: 18
  • Explanation : odd numbers in an given number is 7,3,3,5 and sum is 18

Working :

  • Step 1: Read the integer input
  • Step 2: initialize s and set it to zero
  • Step 3: using modulo with 10 logic we will get last digit of the number 
  • Step 4: Do this operation by using while loop
  • Step 5: Check whether the number is odd or not , if number is odd add to the result
  • Step 6: Print the resultant sum

Python code:

Solution 1:

n=int(input(“Enter the number : “))
s=0
while n>0:
    n1=n%10
    if(n1%2==1):
        s=s+n1
    n=n//10
print(“Sum of odd numbers in given number :”,s)
Enter the number : 8734835
Sum of odd numbers in given number : 18

Working :

  • Step 1: Read input as string
  • Step 2: Initialize a variable and set it to zero
  • Step 3: Traverse through the string if the given character is odd (check by converting character to string by integer)
  • Step 4: If character is odd add to the result
  • Step 5: Print the resultant sum

Solution 2:

n=input(“Enter the number : “)
s=0
for i in n:
    if int(i)%2==1:
        s+=int(i) 
print(“Sum of odd numbers in given number :”,s)
Enter the number : 8734835
Sum of odd numbers in given number : 18