How do you add odd numbers up in Java?

  • Context: Comp Sci 
  • Thread starter Thread starter KillaKem
  • Start date Start date
  • Tags Tags
    Java Numbers
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 4K views
KillaKem
Messages
22
Reaction score
0
I want to add all odd numbers in a number n(ie if n=123456, then i am lookin' for 1+3+5=8)
I have written a small program and it won't work i don't know why!How do i solve my prob?

public class Odd
{
public static void main(String[] args)
{
int n = 3; // just set n to any number

int x = 1;
int num_digits = 0;

while (n/x != 0)
{
x *= 10;
num_digits++;
}

x = 0;

int num;
int sum = 0;

while ( x < num_digits );
{
num = n%10;
n = n/10;

if ( num%2 != 0)
{
sum = sum + num;
}
x++;
}


System.out.printf("%d%n", sum);

}
}
 
Physics news on Phys.org
KillaKem said:
I have written a small program and it won't work i don't know why!
So fix that! Try printing a lot more things, to see if they are giving the results you expect or not. Or use a debugger to step through and monitor what value things have.