"Z Code Writer" is an Online Blog for Programmer & Beginner. Here, You will Find tech, Build your Programming Skills and other Programming Language Like C, C++, HTML, Java Script Java Code, Web Designing and University Of Sialkot (USKT) CGPA / GPA Calculator etc.

Sunday 26 July 2020

The Switch Statement

The switch Statement

        The 'switch' statement is another selection structure in programming language. It can be used as alternative of if else if structure. We can used this when we have multiple option given and we need to select one option in the given.
        For example, usually, this structure is used for menu selections.
        The 'switch' structure contains only one expression at its beginning and multiple cases within its body. Each case contains a set of statements.
The general syntax of 'switch' structure is as follows:
             switch (expression)
            {
                       case label 1 :
                               set of statements-1
                               break ;
                        case label 2 :
                                set of statements-2
                                break ;
                        ---    ---------------------
                        ---    ---------------------
                        default:
                                   set of statements-n
             }

Flowchart of 'switch' Structure

        The flowchart of switch structure is as follows:
flowchart-switch-statement
Flowchart Switch Statement



The 'break Statement

        The 'break' statement is used to exit from the body of the 'switch' structure. In the 'switch' structure, the 'break' statement is normally used at the end of statements in each case. If all 'break' statements are omitted from the 'switch' structure, then the statements of all remaining cases that come after the matched case are also executed.

Difference Between 'switch' and Nested 'if-else' Structures

The 'switch' Structure

  • It is easy to use and to understand.
  • It can be used for only simple menu selections.
  • It is fast because computer evaluates only one expression.
  • it uses single expression which returns a single integer value or a single character.

Nested 'if-else' Structure

  •  It is complicated. It is difficult to use and to understand.
  • It uses multiple expressions and each returns are true or false value.
  • It is very slow because computer evaluates more than one expire.
  • It can used for complicated multiple choices.

No comments:

Post a Comment

Thanks For Visiting Here...!! I will Reply you as soon as possible.