Triangle Pattern Program

Write a menu-driven program to perform the following tasks:

  1. Enter 1 to draw the given triangle.
  2. Enter 2 to draw the inverted triangle.
  3. Enter 3 to Exit.
         9
        898
       78987
      6789876
     567898765
    45678987654
   3456789876543
  234567898765432
 12345678987654321
import java.io.*;
class Triangle{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("1. Enter 1 to draw triangle");
        System.out.println("2. Enter 2 to draw inverted triangle");
        System.out.println("Enter 3 to exit");
        int choice = Integer.parseInt(br.readLine());
        switch(choice){
            case 1:
            for(int i = 9; i >= 1; i--){
                for(int s = 1; s <= i - 1; s++)
                    System.out.print(" ");
                for(int j = i; j <= 9; j++)
                    System.out.print(j);
                for(int k = 8; k >= i; k--)
                    System.out.print(k);
                System.out.println();
            }
            break;
            case 2:
            for(int i = 1; i <= 9; i++){
                for(int s = 1; s < i; s++)
                    System.out.print(" ");
                for(int j = i; j <= 9; j++)
                    System.out.print(j);
                for(int k = 8; k >= i; k--)
                    System.out.print(k);
                System.out.println();
            }
            break;
            case 3:
            System.out.println("Bye...");
        }
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: