answersLogoWhite

0

int sumDigits(int n) {
int sum = 0;

while( n > 0 ) {
sum += (n % 10); // add last digit of n to sum
n /= 10; // divide n by 10 to "chop off" the last digit

}

return sum;

}

____________________________________________________

C program to find the sum of entered digit: By Jatinder Pal Singh

#include
#include
void main()
{
clrscr();
int n,num,x,sum=0;
printf("Enter a number=");
scanf("%d",&n);
while(n>0)
{
x=n%10;
sum=sum+x;
n=n/10;
}
printf("Sum of digits of a number=%d",sum);
getch();
}
User Avatar

Wiki User

15y ago

What else can I help you with?

Continue Learning about Engineering

How many positive integers less than 1000 have no odd decimal digits?

52


Sum of all the digits of the integers from 1 to 2008?

The answer is 28 054


How do you show a positive integer for example 12345678901234567890 in C sharp that has more than 17 digits?

There is Int64 class, it will do it.


Write a c plus plus program that inputs 5 integers from the user and separates the integer into individual digits and prints the digits separated from one another by three spaces each.?

// create an BufferedReader from the standard input stream BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String currentLine = ""; int total = 0; int[] ints = new int[5]; // read integers while (total < 5) { // get input System.out.print("Input an integer: "); currentLine = in.readLine(); // parse as integer try { int input = Integer.parseInt(currentLine); ints[total] = input; ++total; } catch (final NumberFormatException ex) { System.out.println("That was not an integer."); } } // print each number for (int i = 0; i < ints.length; ++i) { // get individual digits if (ints[i] == 0) { System.out.println(0); } else { while (ints[i] > 0) { System.out.println(ints[i] % 10); ints[i] /= 10; } } } Note that this prints out the digits in reverse order (2048 will print 8 first and 2 last).


How do you extract digits from an integer in java?

There are different ways to do it. One is to convert it to a String, then use the string manipulations methods to extract individual digits as strings. You can then convert them back to numbers. Another is to do some calculations. For example, to get the last digit: int i = 12345; int lastdigit = i % 10; //To get additional digits, divide by 10 and repeat: i /= 10; int lastdigit = i % 10; In this case you can create a loop for this (repeating while i > 0), and copy the digits to an array.