Tuesday 16 February 2016

Java: Draw Hollow Triangle - Left Justified java program.

Problem: Hollow Triangle.

Draw a hollow right angled triangle of a given height.

Sample Input:
5
Sample Output:
1
12
1  3
1    4
12345

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter any Int Num:");
  int n = sc.nextInt();
  System.out.println();

  // Hollow Triangle - Left Justified

  for (int i = 1; i <= n; i++) {

   for (int j = 1; j <= i; j++) {

    if (i > 2 && i < n) {
     if (j > 1 && j < i)
      System.out.print(" ");
     else
      System.out.print(j);
    } else
     System.out.print(j);
   }
   System.out.println();
  }

  sc.close();
 }

}




Console:

Enter any Int Num:5

1
12
1  3
1    4
12345

Happy Coding :)
-@D