Program to Find the Sum of Digits of a Number

Problem Statement: Write a C program to find the sum of digits of a given number.

Description:
This program calculates the sum of the digits of a number. It uses a loop and arithmetic operations to extract each digit of the number, add them together, and return the sum.

Usage:
The user enters a positive integer, and the program calculates the sum of its digits and displays the result.

Code:

C
#include <stdio.h>

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

    // Asking user to input a number
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    // Extracting and summing the digits
    while (num != 0) {
        digit = num % 10;  // Get the last digit
        sum += digit;      // Add the digit to the sum
        num /= 10;         // Remove the last digit from the number
    }

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

    return 0;
}

Explanation:

The program calculates the sum of digits of a given number by using a while loop to repeatedly extract the last digit and add it to the sum.


Code Breakdown:

#include <stdio.h>
This line includes the standard input/output library, which allows the program to perform input and output operations.

int main()
This defines the main function where the execution of the program begins.

int num, sum = 0, digit;

  • num: stores the input number from the user.
  • sum: holds the sum of the digits, initialized to 0.
  • digit: used to store each extracted digit.

printf("Enter a positive integer: ");
This prompts the user to enter a number.

scanf("%d", &num);
The program reads the user input and stores it in the variable num.

while (num != 0)
The while loop continues to run as long as the number is not zero. It extracts and sums the digits of the number.

digit = num % 10;
This extracts the last digit of the number using the modulus operator (%).

sum += digit;
The extracted digit is added to the sum.

num /= 10;
This line removes the last digit of the number by dividing it by 10.

printf("Sum of digits = %d\n", sum);
This prints the sum of the digits.

return 0;
This indicates that the program executed successfully.

Sample Input/Output:

Input:

Enter a positive integer: 1234

Output:

Sum of digits = 10

Summary:

This medium-level C program reads a positive integer from the user and calculates the sum of its digits using arithmetic operations. It demonstrates how to handle loops and repeated operations efficiently in C programming.

Test here:

Leave a Reply

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