Write a C program to find the sum of digits of a positive integer.


 

Problem Statement:

Write a C program to find the sum of digits of a positive integer.

Requirements:

  • The program should prompt the user to enter a positive integer.
  • It should calculate and display the sum of the digits of the entered number.
  • For example, if the input is 123, the sum of its digits would be 1 + 2 + 3 = 6.
  • The program should handle both single-digit and multi-digit positive integers.

Example:


  
Enter a positive integer: 456
Sum of digits of 456 is: 15
   

Constraints:

  • The input integer should be positive.
  • Handle cases where the input is 0 separately, as the sum of the digits of 0 is also 0.


  #include 

// Function to find the sum of digits of a number
int sumOfDigits(int n) {
    int sum = 0;
    while (n != 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num < 0) {
        printf("Error: Please enter a positive integer.\n");
    } else {
        int sum = sumOfDigits(num);
        printf("Sum of digits of %d is: %d\n", num, sum);
    }

    return 0;
}
This program defines a function sumOfDigits() to calculate the sum of digits of a given number. In the main() function, it prompts the user to enter a positive integer, calls the sumOfDigits() function to calculate the sum of its digits, and displays the result. If the user enters a negative number, it displays an error message.

0 Comments

Post a Comment

Post a Comment (0)

Previous Post Next Post