In: Computer Science
The CASE structure is a selection structure, however not all selection structures may be represented as CASE. Give an example of a selection problem that may be solved using the CASE structure and another selection problem that CANNOT be represented by the CASE structure. Type your response in the space provided (after you have created a thread). Indicate which problem CAN and CANNOT be represented by CASE Provide an explanation why each of your suggested problem fits the appropriate category.
solution:
CASE Structure(Switch Case) is one of the selection control approach we can use instead of if...else statement
Both Switch and if..else can bes used for making decisions
It will execute the program according to the values
General Form
switch(expression)
{
case x:
//statements
Break;
case y:
//statements
break;
default:
//statements
}
Switch case statement reducing the complexities of if else statement
Switch case structure should be used where the same code needs to be used for more than one condition therefore several if else statements are needed
For example we want to print the day of the week for a given number entered by the user
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int day;
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number:");
day = sc.nextInt();
switch (day)
{
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Please enter theInvalid input");
break;
}
}
}
Screenshot
Output
If the same program written using if else statement 7 comparisons are needed that will create complexity in the code
Therefore switch case is the perfect choice
The drawback of case structure is
It will operate only on integer values
It cannot be used with float or string values
It can be used only with fixed value
Example
For example consider the program to find the grade of subjects when the user entered
The program will be using the logic
average>=80 then print Grade A
average<80 and average>=60 print Grade B
average<60 and average>=40 print Grade C
Else
Print Grade F
These kind of problems we can’t use switch the reason is average is using float value and in some ranges there are grades determined
Therefore if else will be appropriate for this situation
please give me thumb up