Wednesday, September 16, 2020

Switch statement exapression with example

 Switch statement :


We know that when one of the many alternative are to be selected, we can use ladder if statement to control the selection.

However the complexity of such a program increases when the no.of alternative increases.

The program become difficult to read and follow.

At time, it may confuse even the person who designed it.

Therefore c have a built-in multiway decision statement known as switch.

The switch statement test the value of a given variable against a list of case values and when a match is found, a block of statement associated with that case is executed.

The general format of switch statement is.

Switch (expression)

{

      case value - 1 :

                block - 1

                break ;

      case value - 2 :

               block - 2

               break ;

     .  .  .  .  .

     .  .  .  .  .

     default :

                     default - block

}

statement - x ;

The expression is an integer expression or characters.

Value 1, value 2, value 3. . .are constants or constant the expressions and are known as case labels .

Each of should be unique within a switch statement.

Block-1, block-2, block-3,.....are statement lists that contain zero or more statements.

Case labels end with a colon ( : ) .

When the switch is executed, the value of the expression is compared with the values value-1 , value-2 , value-3 ,.....

If a case is found whose value matches with the value of expression, then the block of statements that follows the case is executed.

The break statement at the end of each block causes an exit from the switch.

The default is an optional case, when present it will be executed if the value of the expression does not match with any of the case value.

If not present , no action takes place if all matches fail and the control goes to the statement after the switch statement .

The selection process is illustratedin the following flowchart.

Consider the following example

switch( digit )

{

       case 1:

                printf("one ");

                break;

       case 2:

                printf( two );

                break;

       case 3:

               printf( three );

               break;

      case 4:

              printf( four );

              break;

      case 5:

             printf( five );

             break;

}

In above example the value of variable digit will be displayed in words.



No comments:

Post a Comment

Object Paradigm Oriented Programming in C++ / object oriented programming / History of C++/ paradiagram in c++/C devolop, Operating System, Unix operating system, Assembly language, popular in world, Programming language.

  Object Paradigm Oriented Programming  Two programmers, Brian Kernighan and Dennis Ritchie developed a new language called C, in 1972.  C l...