rss ss rss ss - 4 days ago 6
Java Question

Printing pyramid pattern out of characters

I need to print an array of characters in a pyramid shape. What I have so far is this:

char[] chars = {'F', 'E', 'L', 'I', 'Z', ' ', 'A', 'N','I', 'V', 'E', 'R', 'S', 'A', 'R', 'I', 'O'};
int length = chars.length;


for (int i = 1; i < length; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");

for (int j = 0; j < i; j++)
System.out.print(chars[j]);

System.out.print("\n");
}
for (int i = length; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");

for (int j = 0; j < i; j++)
System.out.print(chars[j]);

System.out.print("\n");


and it prints this:

F
FEL
FELIZ
FELIZ A
FELIZ ANI
FELIZ ANIVE
FELIZ ANIVERS
FELIZ ANIVERSAR
FELIZ ANIVERSARIO
FELIZ ANIVERSAR
FELIZ ANIVERS
FELIZ ANIVE
FELIZ ANI
FELIZ A
FELIZ
FEL
F


But I need it to start printing from the character in the middle of the array. The end result gotta be like this:

I
NIV
ANIVE
ANIVER
Z ANIVERS
IZ ANIVERSA
LIZ ANIVERSAR
ELIZ ANIVERSARI
FELIZ ANIVERSARIO
ELIZ ANIVERSARI
LIZ ANIVERSAR
IZ ANIVERSA
Z ANIVERS
ANIVER
ANIVE
NIV
I


Any help would be greatly appreciated.

Answer

You can do the same thing as show on below code. It will use lesser number of for loops.

char[] chars = { 'F', 'E', 'L', 'I', 'Z', ' ', 'A', 'N', 'I', 'V', 'E', 'R', 'S', 'A', 'R', 'I', 'O' };
    int length = chars.length;


    for (int line=0;line<=length;line++) {
        //This will print upper part of pyramid
        if(line < length/2){
            String output="";
            int middelVal=length/2;
            for (int i = middelVal - line; i > 0; i--) {
                output=output+" ";
            }
            for (int i = middelVal - line; i <= middelVal + line; i++) {
                output=output+chars[i];
            }
            System.out.println(output);
        }else if(line > length/2){
            //This will print lower part of pyramid
            String output="";
            int middelVal=length/2;
            int nwNum = chars.length-line;
            for (int i = middelVal - nwNum; i > 0; i--) {
                output=output+" ";
            }
            for (int i = middelVal - nwNum; i <= middelVal + nwNum; i++) {
                output=output+chars[i];
            }
            System.out.println(output);
        }
    }
Comments