2. Write a program that:
prompt the user for a string
extract all the digits from the string.
If there are digits :
A sum the collected digits together
print out :
• the original string • the digits the sum of the digits
If there are no digits:
print the original string and a message "has no digits".
Answers
(Answered in Python) :
a = input("Enter a string : ")
l = len(a)
sum = 0
for i in range(len(a)) :
if a[i].isdigit == true : #take care of indentation
sum = sum + a[i]
if sum == 0:
print("The original string is : ",a, " and has no digits ." )
else :
print("Original string : ",a, "and the sum of digits =", sum)
#end of program ----------x------------x-------------x------------
#Hope it helps
#Thank You
#Please mark as brainliest
Below are the program in python for the above problem:
Explanation:
Sum=0 #Intialize a starting sum value as 0.
Input= input("Enter the string: ") #Take a input from the user.
if Input.isalpha(): #If condition to check that the string holds the digits or not.
print(Input+" has no digits")
else: #If the string holds the digits, it will excute this line.
for x in Input: # For loop to scan the string charcter by character.
if not x.isalpha():#If condition to check the digits.
Sum=Sum+int(x) #add the digits.
print("The original string is : "+Input+" And The sum of the digits is: "+str(Sum) ) #prints the sum of the digits.
Output:
- If the user inputs "Hellow", then it will prints "There are no digits".
- If the string inputs "Hellow123", then it will prints "The sum=6".
Code Explanation:
- The above code is in python, which holds the if and else statement.
- The "if statement" is used to check that the string holds the digits or not.
- Then the else statement uses a for loop and scan the character one by one and then check the character that it is a digit or not by if statement.
- Then add the digits and print it.
Learn More:
Python program: https://brainly.in/question/5558161