Write a menu driven program to perform the following operations as per user's choice: (i) To print the value of c = a^2 + 2ab, where a varies from 1.0 to 20.0 with increment of 2.0 and b = 3.0 is a constant. (ii) To display the following pattern using for loop: A AB ABC ABCD ABCDE Display proper message for an invalid choice.
Topic: Menu-driven program with switch
Answer
import java.util.Scanner;
class MenuDriven { public static void main(String args[]) { Scanner sc = new Scanner(System.in);
System.out.println("1. Value of c = a*a + 2*a*b"); System.out.println("2. Display the pattern"); System.out.print("Enter your choice (1 or 2) : "); int ch = sc.nextInt();
switch(ch) { case 1: double b = 3.0, c; for(double a = 1.0; a <= 20.0; a += 2.0) { c = a * a + 2 * a * b; System.out.println("a = " + a + " c = " + c); } break;
case 2: for(int i = 1; i <= 5; i++) { for(int j = 1; j <= i; j++) System.out.print((char)('A' + j - 1)); System.out.println(); } break;
default: System.out.println("Invalid choice"); } } }
A menu-driven program is a switch on the user’s choice, with a default branch for anything unexpected — the question explicitly asks for that message, so it carries marks.
Choice 1: note the loop variable is a DOUBLE, since a increases by 2.0 from 1.0 to 20.0. It takes the values 1.0, 3.0, 5.0 ... 19.0, so the loop runs ten times and stops before 21.0. Write the formula as a * a + 2 * a * b; there is no ^ operator in Java for powers.
Choice 2: the row number decides how many letters to print, so the inner loop runs from 1 to i. The letters themselves come from character arithmetic — ('A' + j - 1) gives A, B, C ... and the cast (char) turns the number back into a letter. Without the cast Java would print the ASCII codes 65, 66, 67.
Every case needs its break, or execution would fall through into the next one. The default needs none, being last.
ch int - the menu choice entered by the user a double - loop variable, varying from 1.0 to 20.0 in steps of 2.0 b double - the constant 3.0 c double - computed value of a*a + 2*a*b i, j int - loop variables for the rows and columns of the pattern sc Scanner - object used to read input