Amrinder Brar Amrinder Brar - 5 months ago 16
Java Question

A program that prints the following code

I've been trying to print a pattern in which there is a right triangle and its mirror image and I am unable to figure out the mirror image part.

Pattern:

A A
AB BA
ABC CBA
ABCD DCBA
ABCDEDCBA


Pattern I've been able to print:

A A
AB AB
ABC ABC
ABCD ABCD
ABCDE ABCDE


Here is the code:

public static void main(String args[])
{
int i,j,k,l;
System.out.print("Enter the numbers of rows you want to print: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (i=1;i<=n;i++)
{
int ch = 65,ch1 = 65;
for (j=1;j<=i;j++)
{
System.out.print((char)ch);
ch++;
}
for (k=n;k>=i+1;k--)
{
System.out.print(" ");
}

for (l=1;l<=i;l++)
{
System.out.print((char)ch1);
ch1++;
}
System.out.println("");
}
};

Answer

Comments to your code:

  • i,j,k,l; What is this? Did you forget the type, i.e. int i,j,k,l;? If so, remove the line, and declare the variables where they are used, e.g. for (int i=1;i<=n;i++).
    You can then also reuse the variable names.

  • If you want ch to be a char, why not make it a char? You should also use 'A' to initialize it, not 65.

  • Why do you need two ch variables? Just use one.

  • Last two points are moot, since you should just calculate the value directly, e.g. (char)('A' + j).

  • Now that you've done that, the last loop should count backwards, to get letters in reverse order. (mirror image part)

  • Since you want middle letter (E in your example) to only print once, that means you need odd number of spaces when not printing E and no spaces when printing the single E. Easiest way to do that, is for last line to be handled separately.

  • No need to add empty string when printing newline, i.e. println("")println().

  • Don't put ; after your method, i.e. };}.

This is the result:

public static void main(String args[]) {
    System.out.print("Enter the numbers of rows you want to print: ");
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    // Print lines 1 to n-1
    for (int i = 1; i < n; i++) { // count up (i = 1 .. n-1)
        for (int j = 0; j < i; j++) { // count up (j = 0 .. i-1)
            System.out.print((char)('A' + j));
        }
        for (int j = 1; j < 2 * (n - i); j++) { // odd number of spaces
            System.out.print(' ');
        }
        for (int j = i - 1; j >= 0; j--) { // count down (j = i-1 .. 0)
            System.out.print((char)('A' + j));
        }
        System.out.println();
    }
    // Now print last line
    for (int j = 0; j < n; j++) { // count up (j = 0 .. n-1)
        System.out.print((char)('A' + j));
    }
    for (int j = n - 2; j >= 0; j--) { // count down (j = n-2 .. 0)
        System.out.print((char)('A' + j));
    }
    System.out.println();
}
Comments