Copyright © tutorialspoint.com

Latest C Tutorial

switch statement examples:

previous

Try following example to understand switch statement. You can put the following code into a test.c file and then compile it and then run it .

#include <stdio.h>

main()
{
     int  Grade = 'A';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
        case 'B' : printf( "Good\n" );
        case 'C' : printf( "OK\n" );
        case 'D' : printf( "Mmmmm....\n" );
        case 'F' : printf( "You must do better than this\n" );    
        default  : printf( "What is your grade anyway?\n" );
     }	
}

This will produce following result:

Excellent
Good
OK
Mmmmm....
You must do better than this    
What is your grade anyway?

Using break statement:

You can come out of the switch block if your condition is met. This can be achieved using break statement. Try out following example:

#include <stdio.h>

main()
{
     int  Grade = 'B';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
                   break;
        case 'B' : printf( "Good\n" );
                   break;
        case 'C' : printf( "OK\n" );
                   break;
        case 'D' : printf( "Mmmmm....\n" );
                   break;
        case 'F' : printf( "You must do better than this\n" );
                   break;
        default  : printf( "What is your grade anyway?\n" );
                   break;
     }
}

This will produce following result:

Good

What is default condition:

If none of the conditions is met then default condition is executed. Try out following example to understand default condition.

#include <stdio.h>

main()
{
     int  Grade = 'L';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
                   break;
        case 'B' : printf( "Good\n" );
                   break;
        case 'C' : printf( "OK\n" );
                   break;
        case 'D' : printf( "Mmmmm....\n" );
                   break;
        case 'F' : printf( "You must do better than this\n" );
                   break;
        default  : printf( "What is your grade anyway?\n" );
                   break;
     }
}

This will produce following result:

What is your grade anyway?

previous

Copyright © tutorialspoint.com