C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Menu Driven - Pattern Program - Java Programs

Using the switch statement, write a menu-driven program for the following:
(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
IC
ICS
ICSE

For an incorrect option, an appropriate error message should be displayed.

import java.util.Scanner; class Menu{ public static void main(String[] args){ Scanner in = 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 = Integer.parseInt(in.nextLine()); switch(choice){ 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)); System.out.println(); break; default: System.out.println("Invalid choice!"); } } }

Output

 
 OUTPUT 1: 
1. Floyd's triangle
2. ICSE Pattern
Enter your choice: 1
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
 

 OUTPUT 2: 
1. Floyd's triangle
2. ICSE Pattern
Enter your choice: 2
I
IC
ICS
ICSE