Using the Switch Statement, Write a Menu-driven Program for the Following: (I) to Print Floyd’S Triangle Given Below
Advertisements
Question
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
I C
I C S
I C S E
For an incorrect option, an appropriate error message should be displayed.
Advertisements
Solution 1
(i)
import java.util.Scanner;
class pattern
{
public static void main ()
{
Scanner sc = new Scanner (System. in);
System.out.println("1. Pattern 1 \n 2. pattern 2");
System.out.println ("Enter choice");
int c = sc.nextInt ();
switch (c)
{
case 1 :
int a, b, c = 1;
for (a = 1; a < = 5; a++)
{
for (b = 1; b < = a; b++)
{
System.out.print (c);
C++;
}
System.out.ptintln ();
}
break:
(ii)
String s = "ICSE"; int I = s.length();
for (int i = 0; i < I; i++)
{
for (int j = 0; j < = i; j++)
{
System.out.print (s.charAt(j)),
}
System.out.println ();
}
break;
default:
System.out.println ("Invalid choice");
}
}
}
Solution 2
import java.util.*;
public class Q11{
public static void main(String ag[])
{Scanner ob = new Scanner(System.in);
int p = 1, i, j;
char ch;
System.out.println("***Menu Driven Program using if-else***");
System.out.println("Enter 'a' to Print Floyd's triangle");
System.out.println("Enter 'b' to print the pattern of the word ICSE");
System.out.println("Enter your choice");
ch = ob.next().charAt(0);
System.out.println();
if (ch == 'a' || ch == 'A')
{
for (i = 1; i <= 5; i++)
{for (j = i; j <= i; j++)
System.out.print(p++ + "\t");
System.out.println();
}
}
else if (ch =='b' || ch == "B")
{
String s = "ICSE";
for (i = 0; i <= 3; i++)
{ for (j = 0; j <= i; j++)
System.out.print(s.charAt(j) + " ");
System.out.println();
}}}}