iks_in iks_in - 4 months ago 16
Java Question

Print a center aligned triangle along with upside down triangle in java

I want to print center aligned triangle along with upside down triangle. Output should be this.

1
121
12321
1234321
123454321
1234321
12321
121
1


Though its showing correctly numbers and upper half of the triangle properly centered aligned, its not showing lower half of the triangle in center alignment.Below is my code.

public class Pro1point1
{
public static void main(String[] args){
int i,j,k,l,space=29;
for(i=1;i<=5;i++){
//First print the upper half triangle.
for(j=1;j<=space;j++){
System.out.print(" ");
}
for(k=1;k<=i;k++){
System.out.print(k);
}
for(l=i-1;l>=1;l--){
System.out.print(l);
}
space--;
System.out.println();
}
//Now Print the lower half triangle.

space=29;
for(i=4;i>=1;i--){
for(j=space;j>=1;j--){
System.out.print("");
}
for(k=1;k<=i;k++){
System.out.print(k);
}
for(l=i-1;l>=1;l--){
System.out.print(l);
}
space++;
System.out.println();
}
}
}


It shows me like this.

My Output is like this

Answer

There is a typo in the second for loop, you have to use:

System.out.print(" ");

instead of

System.out.print("");

and since your second for loop starts at 4 you have to set

space=26;
Comments