Tuesday 16 February 2016

Java: Draw Hollow Triangle - Right Justified - Reverse order java program.

Problem: Hollow Triangle - Right Justified

Draw a hollow right angled triangle of a given height.
Sample Input:
5
Sample Output:
        5
      45
    3  5
  2    5
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 - Right Justified - Reverse

  for (int i = n; i >= 1; i--) {

   for (int j = 1; j < i; j++) {
    System.out.print(" ");
   }
   for (int k = i; k <= n; k++) {
    if (i > 1 && i < n - 1) {
     if (k > i && k < n) {
      System.out.print(" ");
     } else
      System.out.print(k);
    } else
     System.out.print(k);
   }
   System.out.println();
  }

  sc.close();
 }

}



Console:

Enter any Int Num:5

        5
      45
    3  5
  2    5
12345

Happy Coding :)
-@D