Skip to main content

Switch-Case in C Program #DOTC_Mdb

Switch-Case in C Program.


Hi Everyone,

Today we will discuss about Switch – Case statement in C Program.  Before going through Switch – Case program please go through my previous blogs for your reference and it will easy for you to write programs by using Switch- Case.

https://dheeraj60.blogspot.com/2020/06/continue-and-break-statement-statement.html

https://dheeraj60.blogspot.com/2020/06/while-and-do-while-loop-lop-in-c.html

https://dheeraj60.blogspot.com/2020/06/nested-for-loop-with-simple-pattern.html

Let’s Start with Switch case:

Switch case is similar to conditional statements where we can give multiple conditions in one statement. In other word switch case statement is used when we have multiple options and we need to perform a different work for all option. Although we can do same thing with IF ELSE which we discussed in previous blog but in switch case we can pass multiple option at one time.

Syntax for Switch –case is as below :

 

switch (expression)

​{

    case constant1:

      // statements

     

    case constant2:

      // statements

          .

        .

    default:

      // default statements

}

 

Note : we can also use break statement in switch which we discussed in my previous blog .

Let’s understand how this Syntax work :

The above expression is evaluated once and compared  the values of each case label .If there is a match, the corresponding statements after the matching label are executed. Any matches happen matching level case are executed and If there is no match, the default statements are executed.

 

Let’s understand with one Simple Program where we declare one variable of integer type with default value and see how Program works and the output.

 

Below is the Program.

 

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

 

  int i=10;

     switch(i+4)

     {

         case 1:

           printf("Case1: Value is: %d", i);

         case 2:

           printf("Case1: Value is: %d", i);

         case 3:

           printf("Case1: Value is: %d", i);

         default:

           printf("Default: Value is: %d", i);

    }

       return 0;

}

 

Here In switch I use variable i and assigned the value of i is 10. I gave i+4, where i value is 10 and after addition the expression resulted 14. As there is no case defined with value 14  so the default case is executed and output will be Default value is: 10.

 

Below is the output of above program in Compiler code-block .

 

  

Now we can use other program using break statement and see how it work and escape the case condition.

 

Below is the Program:

#include <stdio.h>

#include <stdlib.h>

int main()

{

 

  int i=3;

     switch (i)

     {

          case 1:

             printf("Case1 ");

           break;

          case 2:

             printf("Case2 ");

            break;

          case 3:

             printf("Case3 ");

             break;

          case 4:

             printf("Case4 ");

             break;

          default:

             printf("Default ");

     }

       return 0;

}

 

  

Note : if we not use break statement here the output will be Case3 Case4 Default . Since we use break statement so output will be case 3 only . I passed a variable to switch, the value of the variable is 3 so the control jumped to the case 3 . If you not use break statement in the program, all the subsequent cases from case 3 and default statements got executed and value will be Case3 Case4 Default .

 

Below is the output of above program in compiler Code – Block.

 

 

 

Let’s write one meaning program by using switch case with break statement to create a simple calculator for arithmetic operator +, -, * and /  means addition, subtraction, multiplication and division and number’s and operator will pass by user.

Note : Only thing in this program we use  data type  char and double . why i mention here as in previous blogs i only used int and float as data type . So understand char and double here . Char is used for character with 1 byte whereas in double it act as integer only but size is upto 8 bytes. We already know float used for decimal uses and size of float is 4 bytes and size of int is also 4 bytes . That is why we use double here for calculator program where we can take decimal values as well.

 

Program for Small calculator is as below after that we will understand the Program.

Program is as below:

 

#include <stdio.h>

#include <stdlib.h>

int main()

{

   char operatorvalue;

    double i, j;

    printf("Enter an operator (+, -, *, /): ");

    scanf("%c", &operatorvalue);

    printf(" Please enter any two values: ");

    scanf("%lf %lf",&i, &j);

 

    switch(operatorvalue)

    {

        case '+':

            printf("%.1lf + %.1lf = %.1lf",i, j, i+j);

            break;

 

        case '-':

            printf("%.1lf - %.1lf = %.1lf",i, j, i-j);

            break;

 

        case '*':

            printf("%.1lf * %.1lf = %.1lf",i, j, i*j);

            break;

 

        case '/':

            printf("%.1lf / %.1lf = %.1lf",i, j, i/j);

            break;

 

          default:

            printf("Correct operator not given by user:");

    }

 

       return 0;

}

 

 

Here in Program we use char for charactervalue which will accept only one operator that may be addition , subtraction , multiplication or division and we use double for variable i and j which can accept number as well as decimal values. So once user pass the character value for any operand it will work for that only because in switch case we use break statement so it will not go to next statement . Here in this program i am passing – character value and for long i and j i am passing value 17.5 and 2.5  . so  - operator entered by the user is stored in the operator variable. And, two operands 17.5 and 2.5 are stored in variables i and j. Since we pass – operator  so it jumps to case '-': and do the subtraction and also used the break statement so it will terminate after doing this operation only . You can pass any operator and number as per your requirement and see the result. If you pass any other operator apart from - , + , * and / the program will go to default and give you output as Correct operator not given by user:

But here we passing operator – and value 17.5 and 2.5 so output will be 15.0.

 

Below is the output of Above calculator in compiler code- block.

 

 

 

Hope you are able to understand the uses of Switch – cases and benefits of break in using switch – cases statement programs. Please go through this blog carefully as switch – cases  play important role in C programming and it’s vastly used in programs so try to write as much program as you can and let me know if any doubts  and also we will see it’s uses in other topics/blog as well. In next Blog i will come up with go to statement in C and Basic Concept of Array.

Please Let me know if you have any doubts.

Thanks.


Comments

Popular posts from this blog

SQL and Classification of SQL in Oracle Database #Diksha Oracle Training Centre

  SQL and Classification of SQL in Oracle Database.   SQL is Structured Query Language , which is used for storing, manipulating and retrieving data stored in a relational database .SQL is the standard language for RDBMS. All the Relational Database Management Systems (RDMS) like Oracle, MySQL, Sybase, Informix, IBM DB2 and Microsoft SQL Server use SQL as their standard database language. Oracle is one of the more secured database as compared to other databases. Importance of   SQL : SQL and PL/SQL is a backend process where all data is stored and retrieved in GUI which created either by any programming languages like Java, C++, PHP etc. so we need to have very secure database so that there will be no impact for users. SQL allows users to access data in the relational database management systems. SQL is used to communicate with a database.SQL and PL/SQL allows users to create and drop databases tables , views , stored procedures , functions , packages , trigger et...

Materialized View uses and Benefits in Database #DOTC_Mdb

Materialized View uses and Benefits in Database. Hello Everyone, Today we will discuss about Materialized view as it’s play important role in database. We already discussed about Simple Views and complex views in my previous blog. Before Materialized view go through my previous blog which related to simple view. https://dheeraj60.blogspot.com/2020/05/benefits-of-creating-and-using-view-in.html As we know View is not a database object and not like table which is stored in database, but view can be created from base table a view is an SQL statement that’s stored in the database. This statement, or view, has a name.A view looks and acts a lot like a table. It has columns and rows, and can be included in SELECT queries just like a table. In other word we can say View is a virtual/logical table which is basically used for security purpose. Let’s understand   about   Materialized view : A materialized view is a view that stores the results of the view’s query. Whenever you que...

Top 50 Interview Questions On SQL and PL/SQL #DOTC_Mdb

                    Top 50 Interview Questions On SQL and PL/SQL. Today we will Discuss Top 50 interview questions and answers of SQL and PL/SQL which is frequently asked in interview.     Question 1: What is SQL and Classification of SQL? Answer SQL is a Structure Query Language which is vastly used in RDBMS database like Oracle, Sybase, DB2 , Microsoft SQL server etc.   Classification of SQL is as below: DDL (Data Definition Language):  Commands are  create , alter , drop , truncate etc DML (Data Manipulation Language) : Commands are  insert,update and delete . TCL (Transaction Control Language ) : Commands are  Commit , Rollback and Save point. DCL (Data Control Language) : Commands are Grant , Revoke Question 2:    What is meant by Joins? What are the types of join? Answer Joins are basically used to extract/get data from multiple tables using s...