KnowledgeBoat Logo

Computer Applications

Write a program to generate a triangle or an inverted triangle till n terms based upon the user's choice.

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:
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
Enter your choice 2
Enter the number of terms 6
Sample Output:
6 6 6 6 6 6
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1

Java

Java Nested for Loops

67 Likes

Answer

import java.util.Scanner;

public class KboatPattern
{
    public void choosePattern() {
        
        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 ch = in.nextInt();
        
        System.out.print("Enter the number of terms: ");
        int n = in.nextInt();
        
        switch (ch) {
            case 1:
            for (int i = 1; i <= n; i++) {
                for (int j = 1; j <= i; j++) {
                    System.out.print(i + " ");
                }
                System.out.println();
            }
            break;
            
            case 2:
            for (int i = n; i > 0; i--) {
                for (int j = 1; j <= i; j++) {
                    System.out.print(i + " ");
                }
                System.out.println();
            }
            break;
            
            default:
            System.out.println("Incorrect Choice");
        }
    }
}

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. 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: 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 Enter your choice 2 Enter the number of terms 6 Sample Output: 6 6 6 6 6 6 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1BlueJ output of Write a program to generate a triangle or an inverted triangle till n terms based upon the user's choice. 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: 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 Enter your choice 2 Enter the number of terms 6 Sample Output: 6 6 6 6 6 6 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1

Answered By

25 Likes


Related Questions