Using the switch statement, write a menu-driven program for the following: (i) To print Floyd's triangle (given below): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (ii) To display the following pattern: I IC ICS ICSE For an incorrect option, an appropriate error message should be displayed.
Topic: Menu-driven program — Floyd's triangle and pattern
Answer
import java.util.Scanner;
class MenuPattern { public static void main(String args[]) { Scanner sc = new Scanner(System.in);
System.out.println("1. Floyd's triangle"); System.out.println("2. ICSE pattern"); System.out.print("Enter your choice (1 or 2) : "); int ch = sc.nextInt();
switch(ch) { case 1: int n = 1; for(int i = 1; i <= 5; i++) { for(int j = 1; j <= i; j++) { System.out.print(n + " "); n++; } System.out.println(); } break;
case 2: String s = "ICSE"; for(int i = 0; i < s.length(); i++) System.out.println(s.substring(0, i + 1)); break;
default: System.out.println("Invalid choice"); } } }
Two patterns, each using a different idea.
Floyd's triangle: the numbers run CONTINUOUSLY across the rows — 1, then 2 3, then 4 5 6. So the counter n must be declared OUTSIDE both loops and incremented after every print; it must not restart at each row. That single decision is what makes it Floyd’s triangle rather than an ordinary number pattern. The number of values in row i is i, which fixes the inner loop.
The ICSE pattern is far simpler than it looks: each row is just a longer substring of the same word. s.substring(0, i + 1) gives I, IC, ICS, ICSE as i runs from 0 to 3 — no nested loop at all. Recognising when substring() replaces a loop is worth real time in an examination.
The question asks specifically for switch, and the default branch with its error message carries marks.
ch int - the menu choice entered by the user n int - the running counter for Floyd’s triangle i, j int - loop variables for the rows and columns s String - the word "ICSE" used to build the second pattern sc Scanner - object used to read input