0

Situation:

I am trying to convert the following for loop into a while loop:

final int MIN = 1;
final int MAX = 7;
int i=MIN,j=MIN;

for(i=MIN; i<=MAX;i++)
{
    for(j=MIN;j<=MAX;j++)
    {
        if(i==j)
            if(i==(MIN+MAX)/2)
                System.out.print("o");
            else
                System.out.print("*");
        else if (i+j == MIN+MAX)
            System.out.print("*");
        else
            System.out.print(" ");
    }
    System.out.println();
}

I thought it was pretty simple:

while(i<=MAX)
{
    while(j<= MAX)
    {
        if(i==j)
            if(i==(MIN+MAX)/2)
                System.out.print("o");
            else
                System.out.print("*");
        else if (i+j == MIN+MAX)
            System.out.print("*");
        else
            System.out.print(" ");
        j++;
    }
    System.out.println();
    i++;
}

however, for some unknown reason, when i>1, it never goes into the inner while loop. i'm not sure what i'm doing wrong...

1
  • 2
    Use braces (even when they're optional)! Commented Jun 16, 2019 at 0:52

1 Answer 1

2

Every time for loop start it gives j value of MIN. While loop doesn't so you have to replace value after cirtucs of loop. If you did not declare j-MIN; before inner loop, after fist inner loop iteration j would be 8 so it is not <=8

 public static void main(String []args){
    final int MIN = 1;
    final int MAX = 7;
    int i=MIN,j=MIN;

    while(i<=MAX)
    {
        j=MIN;  //ADDED
        while(j<= MAX)
        {
            if(i==j)
                if(i==(MIN+MAX)/2)
                    System.out.print("o");
                else
                    System.out.print("*");
            else if (i+j == MIN+MAX)
                System.out.print("*");
            else
                System.out.print(" ");
            j++;
        }
        System.out.println();
        i++;
    }
    }
Sign up to request clarification or add additional context in comments.

Comments

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.