QUESTION 3 :
Write a program using suitable switch-case and a menu to perform the following operations:
(i) To input a number and print whether it is an Armstrong number or not. (A number
is said to be an Armstrong if sum of cubes of all its digits is equal to the number
itself. Example: Input 153= 18+53+33= 1+125+27= 153, so 153 is an Armstrong number]
(ii) To input a number and print the sum of first and last digits of that number.
Answers
QUESTION 1 (Armstrong number):
To achieve this, we will have to find the sum of the cubes of each digit in the number.
To separate each digit from the number, we can use list(), this separates every characters and makes a list. With this, we can cube all the digits, add them, see if the sum is equal to the number and if it is, we print that the number is armstrong number.
But it is important to keep in mind that list() only works for strings but the input should be taken as an integer.
So, we convert the integer input to a string and then use list() and continue with our code.
CODE:
number = int(input())
number_2 = str(number)
number_2 = [int(x) for x in list(number_2)]
cube_sum = 0
for digit in number_2:
cube_sum = cube_sum + digit**3
if cube_sum == number:
print('Your number is armstrong number')
else:
print('Your number is not an armstrong number')
QUESTION 2(Print the sum of the first and last digit):
Again, to solve this question, we will need to have a string and list it, change all the characters in the list back to integers and then print the sum. To get the first character in a list, we use the index 0 and the last character in the list, we use the index -1.
CODE:
number = int(input())
number = str(number)
number = [int(x) for x in list(number)]
print(number[0] + number[1])