Tuesday 16 February 2016

Java: Draw Triangle - Right Justified java program

Problem: Triangle - Right justified

Draw a right angled triangle of given height.
Sample Input:
5
Sample Output:
        1
      12
    123
  1234
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();

  // Triangle - Right Justified

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

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

    System.out.print(" ");
   }
   for (int k = 1; k <= i; k++) {

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

  sc.close();
 }

}


Console:

Enter any Int Num:5

        1
      12
    123
  1234
12345

Happy Coding :)
-@D