user2424370
user2424370

Reputation:

Printing specified alphabet in pyramid format

I have some problem when trying to print out alphabet XXYY in half pyramid format using Java. Here is the expected output when user entered height of 7:

XX
YYXX
XXYYXX
YYXXYYXX
XXYYXXYYXX
YYXXYYXXYYXX
XXYYXXYYXXYYXX

And here is my code:

public static void main(String[] args){
    int height = 0;
    String display = "";
    Scanner sc = new Scanner(System.in);

    System.out.print("Enter height: ");
    height = sc.nextInt();

    for(int i = 1; i <= height; i++){
        for(int j = 1; j <= i; j++){
            if(j %2 == 0){
                display = "YY" + display;
            }else{
                if(j == 1){
                    display = "XX";
                }
            }
            System.out.print(display);
        }
        System.out.println();
    }
}

What my logic is I thinking to check for even/odd row first then add the XX or YY to the display string. First I check for first row, then I add XX to the display string. Then, if even row, I append YY to the front of the display string.

But my problem is I not sure how to count the amount of XX and YY for each row. Here is my output:

XX
XXYYXX
XXYYXXYYXX
XXYYXXYYXXYYYYXX
XXYYXXYYXXYYYYXXYYYYXX
XXYYXXYYXXYYYYXXYYYYXXYYYYYYXX
XXYYXXYYXXYYYYXXYYYYXXYYYYYYXXYYYYYYXX

Upvotes: 2

Views: 529

Answers (2)

Sameer Mirji
Sameer Mirji

Reputation: 2245

This should do it:

public static void main (String[] args) throws java.lang.Exception
{
    int ht = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter height: ");
    ht = sc.nextInt();

    String text = "";
    for(int i=0; i<ht; i++)
    {
        if (i%2!=0)
            text = "YY" + text;
        else
            text = "XX" + text;
        System.out.println(text);
    }
}

And works with single for loop too!

Upvotes: 1

Mureinik
Mureinik

Reputation: 312219

IMHO, you're over-complicating things. In each row you have the same number of pairs of letters as the row number (one pair on the first row, two on the second, etc). The first row starts with "XX" and then the beginnings alternate between "XX" and "YY". In a similar fashion, within the row, after determining what you started with, you alternate between the two pairs of letters:

for (int row = 0; row < height; ++row) {
    for (int col = 0; col <= row; ++col) {
        if ((col + row) % 2 == 0) {
            System.out.print("XX");
        } else {
            System.out.print("YY");
        }
    }
    System.out.println();
}

Upvotes: 1

Related Questions