Problem Statement - Patterns: ABCDE-ABCD-ABC-AB-A & B-LL-UUU-EEE
Write a menu driven program to display the pattern as per user’s choice.
Pattern 1 Pattern 2
ABCDE B
ABCD LL
ABC UUU
AB EEEE
A
For an incorrect option, an appropriate error message should be displayed.
Solution
TC++ #7196
Run Output
Enter pattern number: 1
Enter number of lines: 5
ABCDE
ABCD
ABC
AB
A
class Pattern {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter pattern number: ");
int choice = scanner.nextInt();
if (choice == 1) {
System.out.print("Enter number of lines: ");
int n = scanner.nextInt();
for (int i = n; i >= 1; i--) {
for (int j = 0; j < i; j++) {
System.out.print((char) ('A' + j));
}
System.out.println();
}
} else if (choice == 2) {
System.out.print("Enter string: ");
String s = scanner.next();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
for (int j = 1; j <= (i + 1); j++) {
System.out.print(ch);
}
System.out.println();
}
} else {
System.out.println("Invalid choice");
}
}
}
-OR-
import java.util.*;
class MenuPattern
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("1. Pattern 1");
System.out.println("2. Pattern 2");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
switch(choice){
case 1:
String s = "ABCDE";
for(int i = s.length(); i >= 0; i--)
System.out.println(s.substring(0, i));
break;
case 2:
s = "BLUE";
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
for(int j = 0; j <= i; j++)
System.out.print(ch);
System.out.println();
}
break;
default:
System.out.println("Invalid choice!");
}
}
}