Tuesday 16 February 2016

Java: Draw a Pyramid / Triangle java program.

Problem: Pyramid Triangle-Isosceles.

Draw a pyramid or triangle of given height.
Sample Input:
5
Sample Output:
        1
      123
    12345
  1234567
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();

  // Triangle - Isosceles pyramid

  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...

    System.out.print(k);
   }
   System.out.println();

  }

  sc.close();
 }

}



Console:

Enter any Int Num:5

        1
      123
    12345
  1234567
123456789

Happy Coding :)
-@D