Everytime I run this nested code, I just get stuck inside of an infinite loop.. any help? I'm not familiar with nested loops at all. I'm supposed to be getting:

public void displayPatternII (int lines) {
       System.out.println("\n\tPattern II\n");
     for (int i = 6; i => lines; i++){
        for (int j = 1; j <=i; j--){


Edited 1 Year Ago by Tierra

When you first enter the outer loop i is equal to 6. You then start the inner loop with j initially being equal to 1. You tell the inner loop to keep going while j is less than or equal to i. With each pass of the loop you subtract 1 from j so j starts at 1 then goes 0, -1, -2 etc so j is always less than i so the loop will never end until something crashes or your numbers flip (not sure how Java handles this as I am not a Java programmer).

PS - Here is a solution in C# - I am sure you can translate it!

void Main()
    for (int i = 6; i  > 0; i--)
        for (int j = 1; j  < i; j++)


I'm not sure why your code is even compiling as the less than sign should be on the left side of the equals sign. This should be how it is in any case, less than, greater than, equal.

Anyway, on with the question, you should be setting one of your initializers in the for loops equal to the amount of lines, then count down. Hope this helps.

read your inner loop carefully.
j starts at 1, then is decreased until it is smaller than i.
i starts at 6, then is increased.
So your inner loop never terminates, as it starts smaller than i, and then is made ever smaller and smaller.

Of course eventually it will end, when the program crashes because of a numeric underflow as j reaches Inter.MIN_VALUE.

This article has been dead for over six months. Start a new discussion instead.