This blog is under construction

Sunday, 23 June 2013

C program to find sum of digits in a given number

Write a C program to find the sum of digits in a given number.


  #include <stdio.h>
  int main() {
        int n, rem, sum = 0;

        /* get the input from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        /* calculate the sum of digits in the given input */
        while (n > 0) {
                rem = n % 10;
                sum = sum + rem;
                n = n / 10;
        }

        /* print the result */
        printf("Sum of digits:%d\n", sum);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for n:123456789
  Sum of digits:45



No comments:

Post a Comment