Sum of digits of a number

We can ask the user to enter a number. We will use one while loop to find out each digit present in the number.

Each step of the loop will collect one digit ( right most ) by dividing the number with 10 and storing the reminder. Each time ( loop ) reminder we will add up by storing in a variable sum.
#include <stdio.h>

int main()
{
 int n, sum = 0, remainder;
 
   printf("Enter an integer");
   scanf("%d",&n);
 
   while(n != 0)
   {
      remainder = n % 10;
      sum = sum + remainder;
      n = n / 10;
   }
 
   printf("Sum of digits of entered number = %dn",sum);
 
return 0;
}

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer