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
Click For Summary
SUMMARY

The discussion focuses on a Java program intended to sum all odd digits of a given integer n. The user provided a code snippet that incorrectly calculates the sum due to a misplaced semicolon in the while loop, leading to an infinite loop. The correct sum for n=123456 should be 9, as the odd digits are 1, 3, and 5. Debugging techniques, such as using print statements or a debugger, are recommended to identify issues in the code.

PREREQUISITES
  • Basic understanding of Java programming
  • Familiarity with control structures (loops and conditionals)
  • Knowledge of integer operations and modular arithmetic
  • Experience with debugging techniques in Java
NEXT STEPS
  • Review Java control flow statements, focusing on while loops
  • Learn about debugging tools in Java, such as IntelliJ IDEA or Eclipse
  • Study modular arithmetic and its applications in programming
  • Explore best practices for writing and testing Java code
USEFUL FOR

Java developers, programming students, and anyone interested in improving their coding skills and debugging techniques.

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 19 ·
Replies
19
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 80 ·
3
Replies
80
Views
10K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K