Comp Sci How do you add odd numbers up in Java?

  • Thread starter Thread starter KillaKem
  • Start date Start date
  • Tags Tags
    Java Numbers
AI Thread Summary
To add all odd digits in a number n in Java, the provided code has a logical error in the while loop that prevents it from executing correctly. The loop condition is improperly terminated with a semicolon, which causes it to run indefinitely without processing the digits. Additionally, the example calculation mistakenly states that the sum of 1, 3, and 5 is 8, when it is actually 9. Debugging techniques, such as printing intermediate values or using a debugger, are recommended to identify issues. Correcting these errors will allow the program to function as intended.
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.
 
KillaKem said:
I want to add all odd numbers in a number n(ie if n=123456, then i am lookin' for 1+3+5=8)
1 + 3 + 5 = 9, not 8.
 

Similar threads

Replies
7
Views
2K
Replies
3
Views
1K
Replies
5
Views
3K
Replies
1
Views
2K
Replies
7
Views
3K
Replies
3
Views
1K
Replies
12
Views
2K
Back
Top