Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
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
C. Sir| Created: 16-Apr-2019 | Updated: 16-Apr-2019|ICSE2016