k_rollo
k_rollo

Reputation: 5472

Printing Half Pyramid of Numbers

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

Answers (5)

HenryDev
HenryDev

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

Ayushi Jha
Ayushi Jha

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

Jeff Anderson
Jeff Anderson

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

ericbn
ericbn

Reputation: 10998

System.out.print(i) instead of System.out.print(j+1)

Upvotes: 2

rafaelc
rafaelc

Reputation: 59284

Change System.out.print(j+1); for System.out.print(i);

Upvotes: 3

Related Questions