Jay.
Jay.

Reputation: 331

Logic problem with the simple nested loop

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;
    }
}

Upvotes: 0

Views: 65

Answers (2)

Villat
Villat

Reputation: 1475

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;
}

Upvotes: 1

Tom Chumley
Tom Chumley

Reputation: 144

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;
 }

Upvotes: 0

Related Questions