Simple calculator Program to learn Switch case statement in C.

Switch Case Statement

switch case statement is a conditional statement in C language. In simple words it gives compiler two make decision from multiple case with the help of a logic switch.

why the need of a Switch case statement???

If else and if else ladder becomes very complex for multiple cases 

In a Switch cases statement 

we make a variable a switch

 switch(a) {

  case i: statement;

  break;

  case ii: statement;

  break;

  default: statement;

}

here the switch statement compares if (a==i) or (a==ii) or if the value of a equals to any of these cases, the statement corresponding to that case gets executed and the execution of that block stops.

if no case matches with the switch than the statement corresponding to default gets executed.

Here is a simple calculator program to learn switch case:

C program for entering numbers and operators to calculate their output.

#include<stdio.h>
int main()
{
    float a,b,c;
    char f;
    printf("enter any no\n");
    scanf("%f",&a);
    printf("enter the operation + * - /");
    scanf(" %c",&f);
    printf("\nenter the second number\n");
    scanf(" %f",&b);
    switch (f)
    {
    case '+':
     c=a+b;
     break;
    case '*':
     c=a-b;
    break;
    case '-':
     c=a-b;
    break;
    case '/':
     c=a/b;
    break;
    default:
     printf("you have entered operators other than + - * /");
    break;
    }
      printf("answer is %f",c);

  return 0;
} 


In the above program we are comparing f with cases, where f is the operator of our expression. if any of the operator matches that operation executes and the value gets saved in c. If none of the case matches the character of switch it prints "You have entered operators other than + - * /"

and hence the answer gets printed.



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.