I'm trying a simple nested loop. For each digit in num1, the inner loop should run. For the following numbers, ideally the output should be:
num1 digit: 7
num2 digit: 4
num2 digit: 3
num1 digit: 5
num2 digit: 4
num2 digit: 3
But it does not run the inner loop for the second time, so it only prints this:
num1 digit: 7
num2 digit: 4
num2 digit: 3
num1 digit: 5
what's wrong with the logic?
num1 = 57;
num2 = 34;
while ( num1 > 0 ) {
digit1 = num1 % 10;
num1 = num1 / 10;
System.out.println("num1 digit: " + digit1);
while (num2 > 0 ) {
digit2 = num2 % 10;
System.out.println("num2 digit: " + digit2);
num2 = num2 / 10;
}
}
num2 = num2 / 10;Modifiesnum2so after the inner loop runs once,num2is zero for subsequent iterations of the outer loop. You need to reset it after the inner loop. Or use a temp variable:int temp = num2; while (temp > 0).....forloop:for (int i = num2; i > 0; i /= 10) {digit2 = i % 10; System.out.println("num2 digit: " + digit2);}This also creates a temp variable (i) but is a bit more compact.