Tuesday 16 February 2016

Java: Draw hollow pyramid java program.

Problem: Hollow Pyramid - Isosceles

Draw a hollow pyramid or triangle - isosceles of a given height.
Sample Input:
5
Sample Output:
        1
    1      3
  1          5
1              7
123456789

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 – Isosceles

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

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

    System.out.print(" ");
   }

   for (int k = 1; k <= ((2 * i) + 1); k++) { // 2n+1= 1,3,5,7...

    if (i > 0 && i < n - 1) {
     if (k > 1 && k < 2 * i + 1) {
      System.out.print(" ");
     } else
      System.out.print(k);

    } else
     System.out.print(k);

   }
   System.out.println();

  }

  sc.close();
 }

}




Console:

Enter any Int Num:
        1
    1      3
  1          5
1              7
123456789

Happy Coding :)
-@D