KnowledgeBoat Logo

Java Pattern Programs

Write a program to generate a triangle or an inverted triangle till n terms based upon the User’s choice of the triangle to be displayed.

Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter the number of terms 5
Sample Output:

* * * * *
  * * * *
    * * *
      * *
        *

Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter the number of terms 5
Sample Output:

A B C D E  
A B C D  
A B C  
A B  
A

Java

Java String Handling

30 Likes

Answer

import java.util.Scanner;

public class KboatTriangleChoice
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Type 1 for a triangle and");
        System.out.println("Type 2 for an inverted triangle of alphabets");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        System.out.print("Enter the number of terms: ");
        int n = in.nextInt();
        
        switch (choice) {
            case 1:
                for (int i = 0; i <= n; i++) {
                    for (int j = 0; j < i; j++) {
                        System.out.print(' ');
                    }
                    for (int k = i; k <= n; k++) {
                        System.out.print('*');
                    }
                    System.out.println();
                }
                break;
            
            case 2:
                n += 64;
                for (int i = n; i >= 65; i--) {
                    for (int j = 65; j <= i; j++) {
                        System.out.print((char)j);
                    }
                    System.out.println();
                }
                break;
            
            default:
                System.out.println("Incorrect choice");
                break;
        }
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program to generate a triangle or an inverted triangle till n terms based upon the User’s choice of the triangle to be displayed. Example 1: Input: Type 1 for a triangle and Type 2 for an inverted triangle Enter your choice 1 Enter the number of terms 5 Sample Output: * * * * * * * * * * * * * * * Example 2: Input: Type 1 for a triangle and Type 2 for an inverted triangle Enter your choice 2 Enter the number of terms 5 Sample Output: A B C D E A B C D A B C A B ABlueJ output of Write a program to generate a triangle or an inverted triangle till n terms based upon the User’s choice of the triangle to be displayed. Example 1: Input: Type 1 for a triangle and Type 2 for an inverted triangle Enter your choice 1 Enter the number of terms 5 Sample Output: * * * * * * * * * * * * * * * Example 2: Input: Type 1 for a triangle and Type 2 for an inverted triangle Enter your choice 2 Enter the number of terms 5 Sample Output: A B C D E A B C D A B C A B A

Answered By

9 Likes