iks_in iks_in - 4 months ago 7
Java Question

Print a triangle of characters in java

I am trying to print a triangle of characters. I want it like this.

A
A B
A B C
A B C D
A B C D E


Below is my code.

public class Pro8Point3
{
public static void main(String[] args){
int space=29;
char ch;
for (int i=1; i<=5; i++) {
ch='A';
//Print spaces in decreasing order. A is at 29th position.
for (int j=1; j<=space; j++) {
System.out.println(" ");
}
//Print Triangle.

for (int k=1; k<=i; k++) {
System.out.print(ch+" ");
ch+=1;
}
space--;
// System.out.println();
}
System.out.println();
}
}


But its not giving me desire output. Please guide me where did I make a mistake over here.

Answer
System.out.println(" ");

should be

System.out.print(" ");

and you should uncomment this line at the bottom of the for loop:

System.out.println();

Final code, fixed up formatting and made the above changes:

public class Pro8Point3
{
    public static void main(String[] args) {
        int space=29;
        char ch;

        for (int i = 1; i <= 5; i++) {
            ch = 'A';  

            //Print spaces in decreasing order. A is at 29th position.
            for (int j = 1; j <= space; j++) {
                System.out.print(" ");
            }

            //Print Triangle.
            for (int k = 1; k <= i; k++) {
                System.out.print(ch + " ");
                ch+=1;
            }

            space--;

            System.out.println();
        }
    }
}

Output:

                             A
                            A B
                           A B C
                          A B C D
                         A B C D E
Comments