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:
123456
12345
1234
123
12
1

``````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--){
System.out.print(j);
}
System.out.println();
}

}
``````

Edited by Tierra

4
Contributors
5
Replies
19
Views
2 Years
Discussion Span
Last Post by jwenting

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++)
{
Console.Write(j);
}

Console.WriteLine(i);
}
}
``````

PS PS - Try changing the 6 to higher values to give you different results.

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.

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.