79.9k views
5 votes
Design a program that asks the user to enter a string containing a series of single digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the string. For example, if the user enters 2514, the method should return 12, which is the sum of 2, 5, 1, and 4. (Hint: The stringToInteger library function can be used to convert a single character to an integer.)

1 Answer

1 vote

Answer:

  1. def calcSum(d):
  2. sum = 0
  3. for x in d:
  4. sum += int(x)
  5. return sum
  6. digits = input("Please enter your digits: ")
  7. print(calcSum(digits))

Step-by-step explanation:

The solution code is written in Python.

Firstly, create a function that take one input digit string (Line 1).

In the function, create a sum variable with initial value 0.

Use a for loop to traverse through each character in the digit string and in the loop use int method to convert each character to integer and add it to sum variable (Line 3-5) and return the sum as output.

Next, use input function to prompt user enter a digit string (Line 7).

Lastly test the function by passing the input digit as argument and print the result (Line 8).

User Ali Abbas
by
7.2k points