Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sum of digits of a number in c

Tags: number digits
  • To find sum of digits of a number in c , we need to get individual numbers and add those numbers.
  • First of all read a number from user using scanf.
  • Using while loop get individual number 
  • Divide the number with 10 so we will get last digit of that number as remainder , once we get that last digit then add it to one variable and divide that number with 10 so it will become one digit less.
  • like this we can get all digits and add all those numbers to get sum of digits 
  • Sum of individual digits in c program
  • c program to find sum of digits of a 3 digit number

correction: here n =number .

# program to find sum of digits of a number in c

  1. #include // include stdio.h
  2. //c program to find sum of digits of a number using while loop
  3. //write a program to find sum of digits of a number
  4. //www.instanceofjava.com
  5. int main()
  6. {
  7.     // declare variables 
  8.     int number, remainder, sum = 0;
  9.     //read input from user 
  10.     printf("Enter a number: ");
  11.     scanf("%d", &number);

  12.    //iterate until number not equal to zero
  13.    // get individual digits and add all those digits to get sum
  14.     while(number != 0)
  15.     {
  16.         remainder = number % 10;
  17.         sum += remainder;
  18.         number = number / 10;
  19.     }
  20.   //print sum of digits in c
  21.     printf("sum = %d", sum);

  22.     getch();
  23. }


Output:
  1. Enter a number
  2. 123
  3. sum = 6




This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

Sum of digits of a number in c

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×