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 C++ 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

Solution
#include <iostream>
using namespace std;

int main() {
    int week;

    /* Input week number from user */
    cout << "Enter week number(1-7): "<<endl;
    cin >> week;

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

    return 0;
}

Problem 2

Write a C++ 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

Till now we have seen finding maximum problems only in if...else questions. Solving the same using switch statement is a bit tricky. Let's see what cases are we going to create ??

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
#include <iostream>
using namespace std;

int main() {
    int num1, num2;

    /* Input two numbers from user */
    cout << "Enter two numbers to find the maximum: "<<endl;
    cin >> num1 >> num2;

    /* Expression (num1 > num2) will return either 0 or 1 */
    switch (num1 > num2) {   
        /* If condition (num1 > num2) is false */
        case 0:
            cout << num2 << " is maximum";
            break;

        /* If condition (num1 > num2) is true */
        case 1:
            cout << num1 << " is maximum";
            break;
    }

    return 0;
}

Problem 3

Write a C++ 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
#include <iostream>
using namespace std;

int main() {
    int num;

    /* Input a number from user */
    cout << "Enter any number to check even or odd: "<<endl;
    cin >> num;

    switch (num % 2) {
        /* If num%2 == 0 */
        case 0:
            cout << "Even Number";
            break;

        /* Else if num%2 == 1 */
        case 1:
            cout << "Odd Number";
            break;
    }

    return 0;
}

Problem 4

Write a C++ 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
#include <iostream>
using namespace std;

int main() {
    char vowel;

    // Input a vowel from the user
    cout << "Enter a vowel (a, e, i, o, u): "<<endl;
    cin >> vowel;

    // Check the value of vowel using a switch statement
    switch (vowel) {
        case 'a':
            cout << "apple";
            break;
        case 'e':
            cout << "egg";
            break;
        case 'i':
            cout << "igloo";
            break;
        case 'o':
            cout << "orange";
            break;
        case 'u':
            cout << "umbrella";
            break;
        default:
            cout << "Invalid vowel";
    }

    return 0;
}

💡
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⚡