I am supposed to print the following output by using loops:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
The highest number in this pattern (in this example, 7) is determined by user input. Here is the applicable code for the pattern:
index=patternLength+1; n=1; //These values are all previously intitialized
while (index!=1) {
index--;
printSpaces((index*2)-2); //A static method that prints a certain number of spaces
while(n!=1) {
n--;
System.out.print(n + " ");
}
System.out.print("\n");
n=patternLength+1-index;
}
And here is the incorrect output for the user input "7":
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
There are two blank lines preceding the incorrect output; these lines have the correct number of spaces necessary for the complete/correct pattern, but for some reason, the actual numbers start printing too "late" in the loop. In other words, the spaces that appear before the "1, 2 1" in the correct example are in the incorrect output. It's some of the numbers that are missing and make the incorrect example incorrect.
n=1sowhile(n!=1)skips immediately and no numbers are printed on the first row. --- At the end of the first iteration,index = patternLength+1 - 1 = patternLength, son=patternLength+1-index = patternLength+1-patternLength = 1, so on the second iteration it will again skip thewhile(n!=1)loop and not print any numbers. --- Which part of that is confusing you, and why couldn't you see that for yourself with a debugger?nis supposed to be. What does the value mean? Is it the count of numbers to print on the current row? If yes, the initial value of1is good, but loop conditionwhile(n!=1)is bad, since you want it to iterate once for a value of1. --- And you should then re-check the formula for calculatingnfor the second iteration, because you'd wantnto be2on the second iteration.