Computer Applications

Write a program to generate a triangle or an inverted triangle based upon User’s choice.

Example 1:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 1
Enter a word : BLUEJ
Sample Output:
B
L L
U U U
E E E E
J J J J J

Example 2:
Input: Type 1 for a triangle and
Type 2 for an inverted triangle
Enter your choice 2
Enter a word : BLUEJ
Sample Output:
B L U E J
B L U E
B L U
B L
B

Java

Java String Handling

22 Likes

Answer

import java.util.Scanner;

public class KboatTriangleMenu
{
    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");
        System.out.print("Enter your choice: ");
        int choice = in.nextInt();
        in.nextLine();
        System.out.print("Enter a word: ");
        String word = in.nextLine();
        int len = word.length();
        
        switch (choice) {
            case 1:
                for(int i = 0; i < len; i++) {
                    for(int j = 0; j <= i; j++) {
                        System.out.print(word.charAt(i));
                    }
                    System.out.println();
                }
                break;
                
            case 2:
                for(int i = len - 1; i >= 0; i--) {
                    for(int j = 0; j <= i; j++) {
                        System.out.print(word.charAt(j));
                    }
                    System.out.println();
                }
                break;
                
            default:
                System.out.println("Incorrect choice");
                break;
        }
    }
}

Variable Description Table

Program Explanation

Output

Answered By

9 Likes


Related Questions