KnowledgeBoat Logo

Java Pattern Programs

Write a menu driven program to generate pattern as follows:

For choice 1:

1
2*3
4*5*6
7*8*9*0

For choice 2:

5****
4###
3**
2#
1

Java

Java Nested for Loops

ICSE

3 Likes

Answer

import java.util.Scanner;

public class KboatPattern
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Type 1 for pattern 1");
        System.out.println("Type 2 for pattern 2");
        System.out.print("Enter your choice: ");
        int ch = in.nextInt();
        
        switch (ch) {
            case 1:
            int t = 1;
            for (int i = 1; i <= 8; i += 2) {  
                for (int j = 1; j <= i; j++) {
                    if (t > 9)
                    t = 0;
                    if (j % 2 == 0)
                        System.out.print('*');
                    else
                        System.out.print(t++);
                }
                System.out.println();
            }
            break;
            
            case 2:
            for (int i = 5; i >= 1; i--) {
                for (int j = 1; j <= i; j++) {
                    if (j == 1)
                        System.out.print(i);
                    else if (i % 2 == 0)
                        System.out.print('#');
                    else
                        System.out.print('*');
                }
                System.out.println();
            }
            break;
            
            default:
            System.out.println("Incorrect choice");
           
        }
    }
}

Output

BlueJ output of Write a menu driven program to generate pattern as follows: For choice 1: 1 2*3 4*5*6 7*8*9*0 For choice 2: 5 4### 3** 2# 1BlueJ output of Write a menu driven program to generate pattern as follows: For choice 1: 1 2*3 4*5*6 7*8*9*0 For choice 2: 5 4### 3** 2# 1

Answered By

1 Like