Switch Case statement in C


Switch Case statement in C

The switch case statement causes a particular group of statements to be selected from a group of options.

The selection is based upon the current value of the expression which is specified with in the switch statement.

The syntax of switch case statement is as follows,

        switch(expression)
        {
                case  label1:
                        statement set 1;
                        break;
                case  label2:
                        statement set 2;
                        break;
               
               
                case  labeln:
                        statement set 3;
                        break;
                default:
                        default statements;
                        break;
        }


The expression whose value is being compared may be any valid expression, including the value of a variable, an arithmetic expression, a logical comparison etc. but not a floating point expression.

The expression’s value is checked against each of the specified cases and when a match occurs the statements following that case is executed.

When a break statement is encountered, control proceeds to the end of the switch case statement.

The break statement should be included in each case. If the break statement is omitted the statements for subsequent cases will also be executed, even though a match has already taken place.
The value that follow the keyword ‘case’ can only be labels, they cannot be expressions.

The case labels cannot be repeated with in a switch statement. The last case default is selected and the statements following this case are executed if none of the cases mentioned earlier are matched.

The default case may or may not be included, depending on the programs needs.

The default group may appear anywhere in the switch statement.

The flow chart of switch statement is as follows,
switch case


Example program 1:

The below program is a program to display the numbers in word from 1 to 5.


Output:




Example program 2:

It is similar to above program but the input only varies, Inspite of 3 the input is 7 here . As it is out of limit 1 to 5 the default is executed. 


Output:




Example program 3:

The switch case program with out break statement. All the statements after the subsequent cases is executed untill the end of switch statement.


Output:




Thank you …


Previous Post
Next Post
Related Posts

0 comments:

Popular Posts