Question 12 of 13intermediate🔧 ApplyLong Answer4 marks

Write a program to find the sum of digits of an integer number, input by the user.

Correct Answer

python #Program to find the sum of digits of an integer number num = int(input("Enter an integer number: ")) sum_digits = 0 original_num = num

while num > 0: digit = num % 10 sum_digits += digit num = num // 10

print("The sum of digits of", original_num, "is", sum_digits)

Output:

Enter an integer number: 12345 The sum of digits of 12345 is 15

Explanation:

The program begins by accepting an integer number from the user using the int(input()) function. A variable sum_digits is initialized to 0 to store the cumulative sum of digits.

Inside the while loop, the condition num > 0 ensures the loop continues until all digits are processed. The modulo operator (%) with 10 extracts the last digit of the number. This digit is added to sum_digits. Then, integer division (//) by 10 removes the last digit from the number.

For example, if the input is 12345, the loop extracts digits 5, 4, 3, 2, and 1 sequentially, adding them to get 15. The loop terminates when num becomes 0.

Exercise: PROGRAMMING EXERCISES | Q: 7
For More Understanding

Explanation

This question tests the student's understanding of loops and arithmetic operators in Python. The solution uses the modulo operator (%) to extract digits and integer division (//) to remove digits, which are fundamental concepts covered in NCERT Class 11 Computer Science. The while loop structure is demonstrated in Program 6-13 of the textbook context, and the modulo operator usage is shown in Program 6-14 for prime number checking.

Solution Steps

  1. Step 1: Accept integer input from user using int(input())

  2. Step 2: Initialize sum_digits variable to 0

  3. Step 3: Use while loop with condition num > 0

  4. Step 4: Extract last digit using num % 10 and add to sum

  5. Step 5: Remove last digit using num // 10

  6. Step 6: Print the final sum of digits