Header Ads Widget

Write a function that return sum of all the odd digits of a given positive no entered through keyboard in Python

 

 Write a function that return sum of all the odd digits of a given positive no entered through keyboard in Python

Given a number , write a function that return sum of all the odd digits of a given positive no entered through keyboard in Python . 

Sample input

4567

Sample Output:

Sum of odd digits of 4567 is: 12

 Write a function that return sum of all the odd digits of a given positive no entered through keyboard in Python

The objective of the code is to write a function that return sum of all the odd digits of a given positive number entered by the user .

Algorithm:-

  1. Define a function that takes an integer as input.
  2. Initialize a variable sum to 0.
  3. Convert the integer to a string.
  4. Traverse the string, check if each character is an odd digit or not.
  5. If it is an odd digit, convert it back to an integer and add it to the sum.
  6. Return the sum.

Code(Python):-

def sum_of_odd_digits(num):
sum = 0
str_num = str(num)
for digit in str_num:
if int(digit) % 2 != 0:
sum += int(digit)
return sum

# Driver code to test the function
num = int(input("Enter a positive integer: "))
print("Sum of all the odd digits of", num, "is", sum_of_odd_digits(num))


Output:-

Enter a positive integer: 4567
Sum of all odd digits of 4567 is 12


Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-

Post a Comment

0 Comments