Using the switch-case statement, write a menu-driven program to do the following: (a) To generate and print letters from A to Z and their Unicode: Letters Unicode A 65 B 66 ... Z 90 (b) Display the following pattern using an iteration (looping) statement: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Topic: Menu-driven program — Unicode table and pattern
Answer
import java.util.Scanner;
class MenuUnicode { public static void main(String args[]) { Scanner sc = new Scanner(System.in);
System.out.println("1. Letters and their Unicode"); System.out.println("2. Display the pattern"); System.out.print("Enter your choice (1 or 2) : "); int ch = sc.nextInt();
switch(ch) { case 1: System.out.println("Letters\tUnicode"); for(char c = 'A'; c <= 'Z'; c++) System.out.println(c + "\t" + (int)c); break;
case 2: for(int i = 1; i <= 5; i++) { for(int j = 1; j <= i; j++) System.out.print(j + " "); System.out.println(); } break;
default: System.out.println("Invalid choice"); } } }
Two useful techniques in one question.
The Unicode table shows that a char can be a LOOP VARIABLE. Writing for(char c = 'A'; c <= 'Z'; c++) works because Java compares and increments characters by their Unicode values. To print the number rather than the letter, cast it: (int)c. Without the cast the tab line would simply print the letter twice.
The pattern is the standard increasing triangle: the row number decides how many values appear, so the inner loop runs from 1 to i, and the value printed is j. Compare it with a pattern of repeated row numbers, where you would print i instead — reading which variable is printed is the whole skill in pattern questions.
The question asks specifically for switch-case, so use it rather than if-else, and include the default branch for an invalid choice.
ch int - the menu choice entered by the user c char - loop variable running from A to Z i, j int - loop variables for the rows and columns of the pattern sc Scanner - object used to read input