Q&A ICSE2016-05A #7319
Question:
Using the switch statement, write a menu driven program for the following: [15]
(i) To print the 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
I C
I C S
I C S E
For an incorrect option, an appropriate error message should be displayed.
Answer:
import java.util.Scanner;
public class Menu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("1. Floyd's triangle");
System.out.println("2. ICSE Pattern");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter n (number of lines): ");
int n = scanner.nextInt();
int currentNumber = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(currentNumber + " ");
currentNumber++;
}
System.out.println();
}
break;
case 2:
System.out.print("Enter word: ");
String word = scanner.next();
for (int i = 0; i < word.length(); i++) {
for (int j = 0; j <= i; j++) {
System.out.print(word.charAt(j) + " ");
}
System.out.println();
}
break;
default:
System.out.println("Invalid choice");
break;
}
}
}
Sample output 1
Floyd’s triangl
ICSE Pattern
Enter your choice: 1
4 Enter n (number of lines): 5
5 1
6 2 3
7 4 5 6
8 7 8 9 10
9 11 12 13 14 15
