Java - Print A Character Triangle

Display/Print A Character Triangle

Description

Display/Print A Character Triangle

a 
a b 
a b c 
a b 
a 

Test cases

You can use the following test cases to verify your code logics.

If input is 3. The output is

a 
a b 
a b c 
a b 
a 

If input value is 10, the output is

a 
a b 
a b c 
a b c d 
a b c d e 
a b c d e f 
a b c d e f g 
a b c d e f g h 
a b c d e f g h i 
a b c d e f g h i j 
a b c d e f g h i 
a b c d e f g h 
a b c d e f g 
a b c d e f 
a b c d e 
a b c d 
a b c 
a b 
a 

Code template

Cut and paste the following code snippet to start solve this problem.


public class Main {
    public static void main(String[] args) {
      test(3);
      System.out.println();
      test(10);
    }
    public static void test(int max) {
       //your code here
    }
}

Answer

Here is the answer to the question above.

Demo

public class Main {
    public static void main(String[] args) {
      test(3);//from   w w  w .  j  a v  a 2s.  c om
      System.out.println();
      test(10);
    }
    public static void test(int max) {
       
      String line = "";
      for (int i = 0; i < max; i++) {
          line += (char)('a' + i) + " ";
          System.out.println(line);
      }
      for (int i = 0; i < max; i++) {
          line = line.substring(0, line.length() - 2);
          System.out.println(line);
      }
    }
}

Related Quiz