Iterate through a number starting at the end and adding every other digit
java
Solution
int num = 12345;
int sum = 0;
int pos = 0;
while(num > 0) {
int digit = num % 10; // make it really blatantly clear what the DIGIT is
if (pos % 2 == 0)
sum += digit;
num /= 10;
pos++;
}
You needed a checking mechanism to ensure you're skipping half the digits. [You're trying to add digits of the number, not numbers. Editor.]
This would also fix your first solution:
if(i%2 /*not num*/ == 0)
Problem
I am working on a school assignment, so I am looking for guidance on what I am doing wrong. This is part of a larger program, but I am trying to work on loop before I implement the rest of the program. Basically, my loop is suppose to iterate through all the number and then add every other number, for example: if the number entered is 48625, then return the sum of 5+6+4. I figured that I would have to combine my loop with an if statement to iterate through each nth number, so this is what I worked out so far: ``` class testLoop{ public static void main (String args[]){ int num = 12345; int sum = 0; for(int i = 0; num > 0; i++) { if(i%num == 0) { sum += num % 10; } num /= 10; System.out.println(sum); } } } ``` Unfortunately, this is not working. It returns 6,5,5,5,5. It is not adding the nth values as planned. I also tried the following: ``` int num = 12345; int sum = 0; while(num > 0) { sum += num % 10; num /= 10; } ``` But that did not work either, it returned 15, which is basically the sum of all digits in variable num. I know I am close to a solution, it's somewhere between my two codes, but I can't seem to get it right.