Chapter #6 – Flow of Control

Class 11 – Chapter 6 Solutions – PROGRAMMING EXERCISES #7
Write a program to find the sum of digits of an integer number, input by the user.
Python Program:
def sum_of_digits(number):
# Convert the number to its absolute value to handle negative numbers
number = abs(number)
total_sum = 0
while number > 0:
digit = number % 10 # Get the last digit
total_sum += digit # Add it to the total sum
number //= 10 # Remove the last digit
return total_sum
# Get user input
try:
user_input = int(input("Enter an integer number: "))
result = sum_of_digits(user_input)
print(f"The sum of the digits of {user_input} is: {result}")
except ValueError:
print("Invalid input. Please enter an integer.")
You can checkout the code from Github here – Programming Exercises – 7
Explanation of the Code:
1. Function Definition: The sum_of_digits function takes an integer number as
input. It uses abs(number) to ensure that it works with negative numbers as
well.
2. Loop: It continues to extract the last digit using number % 10, adds it to
total_sum, and then removes the last digit by performing integer division
(number //= 10).
3. User Input: The program prompts the user to enter an integer. It checks if
the input is valid.
4. Output: If valid, it calls the function and prints the calculated sum of
digits.
Example Output:
Enter an integer number: 123
The sum of the digits of 123 is: 6
NCERT Computer Science Class 11 Chapter 6 Solutions Q 12