Reputation: 5472
public class NestedForLoop {
private void generateNumberPyramid(int num) {
int length = num + 1;
for(int i = 1; i < length; i++) {
for(int j = 0; j < i; j++) {
System.out.print(j+1);
}
System.out.println();
}
}
public static void main(String[] args) {
NestedForLoop nfl = new NestedForLoop();
nfl.generateNumberPyramid(4);
}
}
The output is as follows:
1
12
123
1234
The intended output should be:
1
22
333
4444
What could be going wrong?
Upvotes: 1
Views: 4613
Reputation: 4993
Since you are iterating the ROWS, you should use i and not (j+1). Doing this will simply iterate what you want, otherwise it will keep adding one to each number. so just like this:
for(int i = 1; i < length; i++) {
for(int j = 0; j < i; j++) {
System.out.print(i);
}
System.out.println();
}
Upvotes: 1
Reputation: 4023
The value of i
corresponds to each row. i=1
refers to the first row, i=2
refers to the second row and so on. Therefore in your for loop
, make the following change:
for(int i = 1; i < length; i++) {
for(int j = 0; j < i; j++) {
System.out.print(i);
}
System.out.println();
}
Ideone link: http://ideone.com/5g0xWT
Upvotes: 2
Reputation: 819
Your problem is in the nested for loop:
Change:
for(int j = 0; j < i; j++) {
System.out.print(j+1);
}
To:
for(int j = 0; j < i; j++) {
System.out.print(i);
}
Upvotes: 2