Open In App

Output of C programs | Set 30 (Switch Case)

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Prerequisite – Switch Case in C/C++


Interesting Problems of Switch statement in C/C++

  1. Program 1




    #include <stdio.h>
    int main()
    {
        int num = 2;
        switch (num + 2)
        {
        case 1:
            printf("Case 1: ");
        case 2:
            printf("Case 2: ");
        case 3:
            printf("Case 3: ");
        default:
            printf("Default: ");
        }
        return 0;
    }

    
    

    Output:

    Default: 

    Explanation: In switch, an expression “num+2” where num value is 2 and after addition the expression result is 4. Since there is no case defined with value 4 the default case got executed.

  2. Program 2




    #include<stdio.h>
    void main()
    {
        int movie = 1;
        switch (movie << (2 + movie))
        {
        default:
            printf(" Traffic");
        case 4:
            printf(" Sultan");
        case 5:
            printf(" Dangal");
        case 8:
            printf(" Bahubali");
        }
    }

    
    

    Output:

    Bahubali

    Explanation: We can write case statement in any order including the default case. That default case may be first case, last case or in between the any case in the switch case statement. The value of expression “movie << (2 + movie)" is 8.

  3. Program 3




    #include<stdio.h>
    #define L 10
    void main()
    {
        auto a = 10;
        switch (a, a*2)
        {
        case L:
            printf("ABC");
            break;
      
        case L*2:
            printf("XYZ");
            break;
      
        case L*3:
            printf("PQR");
            break;
      
        default:
            printf("MNO");
      
        case L*4:
            printf("www");
            break;
        }
    }

    
    

    Output:

    XYZ

    Explanation: In C, comma is also operator with least precedence. So if
    x = (a, b);
    Then x = b
    Note: Case expression can be macro constant.

  4. Program 4




    #include<stdio.h>
    void main()
    {
        switch(2)
        {
        case 1L:
            printf("No");
      
        case 2L:
            printf("%s","GEEKS");
            goto Love;
      
        case 3L:
            printf("Please");
      
        case 4L:Love:
            printf("FOR");
        }
    }

    
    

    Output:

    GEEKSFOR

    Explanation: It is possible to write label of goto statement in the case of switch case statement.

This article is contributed by Mr. Somesh Awasthi.



Last Updated : 03 Jun, 2017
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads