From 29377166aea5efcf2cbf783adb1be301d8c13725 Mon Sep 17 00:00:00 2001 From: Ashish Dukare <46935997+ashishdukare@users.noreply.github.com> Date: Sat, 25 Oct 2025 15:53:25 +0530 Subject: [PATCH] Fix digit summation logic and add comments Updated the digit extraction logic to correctly sum individual digits and added comments for clarity. --- digits_sum.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/digits_sum.c b/digits_sum.c index 2ac0700..3138c1c 100644 --- a/digits_sum.c +++ b/digits_sum.c @@ -1,15 +1,26 @@ -#include +#include +/* + Calculates and prints the sum of the digits of an integer entered by the user. + This program prompts the user to enter a number and then uses a while loop + to iteratively extract and sum the individual digits of that number. + prints the Sum of digits + */ + int main() { int num, sum = 0, digit; - printf("Enter a number: "); scanf("%d", &num); while(num != 0) { - digit = num % 100; + // 1. Extract the last digit: The modulo operator (%) gives the remainder when divided by 10. + digit = num % 10; + + // 2. Add the extracted digit to the running sum sum += digit; - num /= 100; + + // 3. Remove the last digit: Integer division (/) by 10 truncates the last digit. + num /= 10; } printf("Sum of digits = %d\n", sum);