#include <stdio.h>

int main() {
    int number, sum = 0, digit;

    // Get user input
    printf("Enter an integer: ");
    scanf("%d", &number);

    // Process the number
    while (number != 0) {
        digit = number % 10; // Get the last digit
        sum += digit;        // Add the last digit to sum
        number /= 10;        // Remove the last digit
    }

    // Display the result
    printf("Sum of the digits: %d\n", sum);

    return 0; // Indicate successful completion
}

Explanation:

Including Libraries:

c

#include <stdio.h>

This line includes the standard input-output library, allowing us to use functions like printf and scanf.

Main Function:

c

int main() { ... }

This function is where the program begins executing. It returns an integer value indicating successful completion.

Variable Declaration:

c

int number, sum = 0, digit;

Here, number stores the user input, sum is initialized to zero to hold the total of the digits, and digit will temporarily store each digit as we process the number.

User Input:

c

printf("Enter an integer: ");
scanf("%d", &number);

We prompt the user to enter an integer and read that value into the number variable.

Calculating the Sum of Digits:

c

while (number != 0) {
digit = number % 10; // Extract the last digit
sum += digit; // Add it to the sum
number /= 10; // Remove the last digit
}

This loop continues until there are no digits left in number. Inside the loop:

We use the modulus operator to get the last digit.
We add this digit to the sum.
We then remove the last digit from number by performing integer division by 10.

Displaying the Result:

c

printf("Sum of the digits: %d\n", sum);

After calculating the sum, we print it out.

OUTPUT :

Enter an integer: 1234
Sum of the digits: 10

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights