Write a menu-driven program to display the pattern as per user’s choice. Pattern 1 ABCDE ABCD ABC AB A Pattern 2 B LL UUU EEEE For an incorrect choice, an appropriate error message should be displayed.
Topic: Menu-driven pattern program
Answer
import java.util.Scanner;
class PatternMenu { public static void main(String args[]) { Scanner sc = new Scanner(System.in);
System.out.println("1. Pattern 1"); System.out.println("2. Pattern 2"); System.out.print("Enter your choice (1 or 2) : "); int ch = sc.nextInt();
switch(ch) { case 1: for(char i = 'E'; i >= 'A'; i--) { for(char j = 'A'; j <= i; j++) System.out.print(j); System.out.println(); } break;
case 2: String s = "BLUE"; for(int i = 0; i < s.length(); i++) { for(int j = 0; j <= i; j++) System.out.print(s.charAt(i)); System.out.println(); } break;
default: System.out.println("Invalid choice"); } } }
Two patterns, each showing a different technique, wrapped in a switch.
Pattern 1 SHRINKS, so the outer loop counts DOWN. Using char loop variables makes it natural: the outer runs from 'E' down to 'A', and the inner always starts at 'A' and runs up to the current outer value. Characters work as loop variables because Java compares and increments them by their Unicode values.
Pattern 2 prints the SAME letter repeatedly, and the letter changes with the row. So the outer loop walks the word "BLUE" with index i, the inner loop repeats i + 1 times, and the character printed is s.charAt(i) — note it is i, not j, inside the inner loop. Reading which variable is printed is the whole skill in pattern questions.
The default branch is explicitly required by the question, so it carries marks.
Note: the printed paper shows five E’s in the last row of Pattern 2, which breaks the 1-2-3-4 progression for a four-letter word. The consistent pattern gives EEEE.
ch int - the menu choice entered by the user i, j char / int - loop variables for the rows and columns s String - the word "BLUE" used to build the second pattern sc Scanner - object used to read input