0

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;
    }
}
3
  • 1
    num2 = num2 / 10; Modifies num2 so after the inner loop runs once, num2 is 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)..... Commented Oct 10, 2019 at 19:30
  • Note, another option is to use a for loop: 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. Commented Oct 10, 2019 at 19:40
  • @JohnnyMopp thanks a lot, your comment was very helpful. Commented Oct 10, 2019 at 19:42

2 Answers 2

1

You're changing the num2 inside the loop, try with something like:

num1 = 57;
num2 = 34;
int tempNum2 = num2;
while ( num1 > 0 ) {

    digit1 = num1 % 10;
    num1 = num1 / 10;
    System.out.println("num1 digit: " + digit1);

    while (tempNum2 > 0 ) {
        digit2 = tempNum2 % 10;
        System.out.println("num2 digit: " + digit2);
        tempNum2 = tempNum2 / 10;
    }
    tempNum2 = num2;
}
Sign up to request clarification or add additional context in comments.

3 Comments

You declare tempNum2 with int twice as a minor fix.
One more minor thing is you still are using num2 in the second while loop at num2 % 10, the code will run but print incorrect results.
@Nexevis well, I should stop answering today, my brain is out of service. Thanks!
0

You need to re-declare the num2 integer within the while loop for num1 > 0 to run the num2 > 0 again;

int num1 = 57;
int 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;
    }

    //Add here
    num2 = 34;
 }

1 Comment

This solution is not optimal as it requires 34 to be hardcoded into the code twice. 34 is most likely not always going to be the value, which is why a temporary variable is ideal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.