C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Generate Triangle / Inverted Triangle Program - Java Programs

Write a program to generate a triangle or an inverted triangle till n terms based upon the user’s choice of triangle to be displayed.
Example 1:
INPUT:
Type 1 for a triangle and type 2 for an inverted triangle
1
Enter the number of terms:
5
OUTPUT:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Example 2:
INPUT:
Type 1 for a triangle and type 2 for an inverted triangle
2
Enter the number of terms:
6
OUTPUT:
6 6 6 6 6 6
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1

import java.util.Scanner; class Triangle{ public static void main(String args[]){ Scanner in = new Scanner(System.in); System.out.println("Type 1 for a triangle"); System.out.println("Type 2 for an inverted triangle"); System.out.print("Enter your choice: "); int choice = Integer.parseInt(in.nextLine()); switch(choice){ case 1: System.out.print("Number of terms: "); int n = Integer.parseInt(in.nextLine()); for(int i = 1; i <= n; i++){ for(int j = 1; j <= i; j++) System.out.print(i); System.out.println(); } break; case 2: System.out.print("Number of terms: "); n = Integer.parseInt(in.nextLine()); for(int i = n; i >= 1; i--){ for(int j = 1; j <= i; j++) System.out.print(i); System.out.println(); } break; default: System.out.println("Invalid choice!"); } } }

Output

 
 OUTPUT 1: 
Type 1 for a triangle
Type 2 for an inverted triangle
Enter your choice: 1
Number of terms: 5
1
22
333
4444
55555 

 OUTPUT 2: 
Type 1 for a triangle
Type 2 for an inverted triangle
Enter your choice: 2
Number of terms: 6
666666
55555
4444
333
22
1