Skip to main content

Control Flow: Practice

Switch Statement

Hello coders : )

Learning and understanding theory is a good way to understand a topic but to get a hold of it, we need practice. Today, in this article we are going to practice a variety of problems upon switch statement. As mentioned in the theory article as well, that switch statements aren't used much in programming problems but let's not undermine their usage as they enable us to write more clean and optimal code than if else ladder.

Prerequisite: Read the 'switch Statement' article in the control flow module

We also solved a few problems upon switch statement while studying about them. Don't forget to solve them as well because they'll help you to clear your basics and more questions means more practice!

Suggestion: For solving switch statement problems, the key is to crack the cases. Always try to search for: What cases are we going to create in this problem? Once cracked, the problem is a cakewalk!

Now let's start solving problems 🚀

Problem 1

Write a Java program to input week number(1-7) and print day of week name using switch case. Assume 1 is equivalent for Monday and 7 for Tuesday.

Input

Enter a number between 1 to 7: 2

Output

Tuesday

Intuition

If you read the theory article of switch statement, then you must have thought of the solution by now. We know that there are 7 days in a week and hence we have 7 options. This implies that 7 cases would be made in our switch statement. In each case, we would be printing the corresponding day.
Example: Monday for case 1, Tuesday for case 2 etc.

Logic

  1. Input day number from user. Store it in some variable say week.
  2. Check the value of week using switch statement i.e. use switch(week) and match with cases.
  3. There can be 7 possible values(choices) of week i.e. 1 to 7. Therefore write 7 case inside switch. In addition, add default case as an else block.
  4. For case 1: print “MONDAY”, for case 2: print “TUESDAY” and so on. Print “SUNDAY” for case 7:.
  5. If any case does not matches then, for default: case print “Invalid week number”

Try it yourself here!

Solution
import java.util.Scanner;

public class PrintDayOfWeek {
    public static void main(String[] args) {
        int week;

        /* Input week number from the user */
        System.out.println("Enter week number(1-7): ");
        Scanner scanner = new Scanner(System.in);
        week = scanner.nextInt();

        switch (week) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Invalid input! Please enter week number between 1-7.");
        }
    }
}

Problem 2

Write a Java program to input two numbers from user and find maximum between two numbers using switch case.

Input

Input first number: 17
Input second number: 25

Output

Maximum: 25

Hint

Remember, when we were learning the switch concepts, there was something written about passing expressions in a switch statement ?? Solution would use that!

Intuition

One thing that I can deduce is that we'll have 2 cases as we only have 2 options to compare. But what 2 cases are we going to create?

Now when we compare any 2 no.s say 1 or 3, we use comparison operater (<, >, =). In c++ language, if the condition is true, it evaluates it as 1 else it evaluates 0. This means that if I print 3>1, output would be 1. If I print 1>3, output is 0.

Try on compiler

Now 2 cases would be based on these values itself, i.e. 0s and 1s. We would pass the value of num1>num2 in our switch statement. This value can only be 0 and 1.

If the value is 0, i.e. case 0, it implies that expression is false and hence num2>num1 implying maximum number is num2.
If the value is 1, i.e. case 1, it implies that expression is true and hence num1>num2 implying maximum number is num1.

Let's understand it with code and don't forget to dry run different examples!

Logic

  1. Input two numbers from user. Store it in some variable say num1 and num2.
  2. Switch expression switch(num1 > num2).
  3. For the expression (num1 > num2), there can be two possible values 0 and 1.
  4. Write case 0 and print num2 is maximum.
  5. Write case 1 and print num1 is maximum

Try it yourself

Solution
import java.util.Scanner;

public class FindMaximumNumber {
    public static void main(String[] args) {
        int num1, num2;

        /* Input two numbers from the user */
        System.out.println("Enter two numbers to find the maximum: ");
        Scanner scanner = new Scanner(System.in);
        num1 = scanner.nextInt();
        num2 = scanner.nextInt();

        /* Expression (num1 > num2) will return either false or true */
        switch (num1 > num2) {
            /* If condition (num1 > num2) is false */
            case false:
                System.out.println(num2 + " is maximum");
                break;

            /* If condition (num1 > num2) is true */
            case true:
                System.out.println(num1 + " is maximum");
                break;
        }
    }
}

Problem 3

Write a Java program to input number from user and check whether the number is even or odd using switch case.

Input

Input number: 12

Output

Even number

Intuition

We know that to check a number say num for odd and even, we check it's divisibility by 2. If the number gives remainder as 1 upon division with 2 (num%2 = 1) then it's odd and if the number gives remainder as 0 upon division with 2 (num%2 = 0) then it's even. Basic maths right?

Ok but where do I apply these conditions? Relating it to the previous problem, we'll pass the expression 'num%2' in our switch statement. Now it's output can be 0 or 1 indicating the 2 cases that we would be making.

But what would these cases do? As we already deduced that if this value = 0 i.e. case 0, then the number is even and so print 'Even number'. And if this value = 1 i.e. case 1, then the number is odd and so print 'Odd number'.

Logic

  1. Input number from user. Store it in some variable say num.
  2. Switch the even number checking expression i.e. switch(num % 2).
  3. The expression (num % 2) can have two possible values 0 and 1. Hence write two cases case 0 and case 1.
  4. For case 0 i.e. the even case print “Even number”.
  5. For case 1 i.e. the odd case print “Odd number”.

Try it yourself

Solution
import java.util.Scanner;

public class CheckEvenOdd {
    public static void main(String[] args) {
        int num;

        /* Input a number from the user */
        System.out.println("Enter any number to check even or odd: ");
        Scanner scanner = new Scanner(System.in);
        num = scanner.nextInt();

        switch (num % 2) {
            /* If num%2 == 0 */
            case 0:
                System.out.println("Even Number");
                break;

            /* If num%2 == 1 */
            case 1:
                System.out.println("Odd Number");
                break;
        }
    }
}

Problem 4

Write a Java program to input vowels and print any word starting from that letter using switch case.

  • You can print any word, provided the starting letter should be the input as provided by the user.
  • Assumption: all inputs are in lower case.

Input

Enter a vowel: a

Output

apple

Intuition

The problem asks to take vowels as input and there are 5 vowels. Now can you guess the number of cases and what will they contain? I hope you guessed it right 😋. There will be 5 cases and each case would contain the 5 vowels. We'll be printing a corresponding word starting from the same vowel.

Logic

  1. Input vowel number from user. Store it in some variable say vowel .
  2. Check the value of vowel using switch statement i.e. use switch(vowel) and match with cases.
  3. There can be 5 possible values(choices) of vowel i.e. a,e,i,o,u. Therefore write 5 case inside switch. In addition, add default case as an else block.
  4. For case 'a': print “apple”, for case 'b': print “egg” and so on. Print “umbrella” for case 'u':.
  5. If any case does not matches then, for default: case print “Invalid vowel”

Try it yourself

Solution
import java.util.Scanner;

public class CheckVowel {
    public static void main(String[] args) {
        char vowel;

        // Input a vowel from the user
        System.out.println("Enter a vowel (a, e, i, o, u): ");
        Scanner scanner = new Scanner(System.in);
        vowel = scanner.next().charAt(0);  // Read a single character

        // Check the value of vowel using a switch statement
        switch (vowel) {
            case 'a':
                System.out.println("apple");
                break;
            case 'e':
                System.out.println("egg");
                break;
            case 'i':
                System.out.println("igloo");
                break;
            case 'o':
                System.out.println("orange");
                break;
            case 'u':
                System.out.println("umbrella");
                break;
            default:
                System.out.println("Invalid vowel");
        }
    }
}
💡
Note: As mentioned previously, switch case codes can also be written using if else ladder statements. Similarly, these solutions can also be written using if else ladder rather than switch statements : )

I hope by now you must be very confident in switch statement concepts and their problems. As already said, switch case isn't much used in actual problem solving as they don't cover variety of problems like in an if...else ladder but is a major concept of c++ programming.

With this, all the concepts of control flow gets over. Get ready to move to the next module! See you there with more energy, more enthusiasm⚡