C programs

C Program for calculator using switch case

In this program we will create a simple console calculator in c using the switch case statement.

Switch is a control statement that allows us multiple gives us multiple choice option on given value. In switch case a value can change control of execution.

Program

#include<stdio.h>

#include<conio.h>

void main()

{

int a,b,c,x;

clrscr();

printf("enter the two numbers :");     //taking two no from user

scanf("%d%d",&a,&b);

printf("1.add\t2.sub\t3.mul\t4.div\n");  //choose one of the operation

printf("choose a number: ",x);

scanf("%d",&x);

switch(x)

{

case 1: x=1;                             //addition perform

      c=a+b;

      printf("addition=%d\n",c);

      break;

case 2:x=2;        

      c=a-b;                             //subtraction perform

      printf("subtraction=%d\n",c);

      break;

case 3:x=3;

     c=a*b;                             //multiplication perform

     printf("multiplication=%d\n",c);

     break;

case 4: x=4;

    c=a/b;                              //division perform

    printf("division=%d\n",c);

    break;

default:

    printf("again choose the number");   //if you choose other no. then 1 to 4 then default run

}

getch();

}

When Run The Program Following Output:

 

enter the two numbers: 20  40                                                                                                   

1.add   2.sub   3.mul   4.div                                                                                                 

choose a number 1                                                                                                             

 

addition=60   

 

Description

In above program we create simple console calculator using switch case statement.

We used the c arithmetic operator to perform addition, sub, mul, div.

Syntax of switch case statement:

switch(var)

‚Äč{

    case const1:

        // block of lines to be executed if var is equal to const1;

        break;

    case const2:

        // block of lines to be executed if var is equal to cons2;

        break;

        .

    default:

        // block of lines to be executed if n does not match any constant

}

Releted Programs

© 2017 codewmAll rights reserved.