C Program to Compute the Sum of Digits in a given Integer

C Program to Compute the Sum of Digits in a given Integer

This C Program computes the sum of digits in a given integer. This program m accepts integer. Then adds all the digits of a given integer, that becomes the sum of digits of integer.
Here is source code of the C program to compute the sum of digits in a given integer. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
  1. /*
  2.  * C program to accept an integer & find the sum of its digits
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main()
  7. {
  8.     long num, temp, digit, sum = 0;
  9.  
  10.     printf("Enter the number \n");
  11.     scanf("%ld", &num);
  12.     temp = num;
  13.     while (num > 0)
  14.     {
  15.         digit = num % 10;
  16.         sum  = sum + digit;
  17.         num /= 10;
  18.     }
  19.     printf("Given number = %ld\n", temp);
  20.     printf("Sum of the digits %ld = %ld\n", temp, sum);
  21. }
$ cc pgm81.c
$ a.out
Enter the number
300
Given number = 300
Sum of the digits 300 = 3
 
$ a.out
Enter the number
16789
Given number = 16789
Sum of the digits 16789 = 31

No comments:

hia friends you are seeing my blogger thank's. Powered by Blogger.