Pages

January 21, 2013

Switch Statement


switch statement banner ON OFF


This statement is also used for decision making. Here key word is switch followed by control variable and followed by it’s block.
In the block of switch statement multiple cases are used and each ends with break statement this is also called as early exit loop.
Out of all the cases only that case will run whose value matches with the control variable.


/*Program to enter two numbers and apply operations of addition, subtraction, multiplication, division and show output*/

#include<stdio.h>
#include<conio.h>
void main()
{
     int n,n1,n2,add=0,sub=0,mul=0,div=0;
     printf("\n enter any two numbers");
     scanf("%d%d",&n1,&n2);
     printf("\n choose 1 for add, 2 for sub, 3 for mul, 4 for divide");
     scanf("%d",&n);
     switch(n)
     {
       case 1:
          add=n1+n2;
          printf("\n addition of two numbers is %d",add);
          break;
                    
       case 2:
          sub=n1-n2;
          printf("\n subtraction of two numbers is %d",sub);
          break;
                    
       case 3:
          mul=n1*n2;
          printf("\n multiplication of two numbers is %d",mul);
          break;
                   
       case 4:
          div= (n1/n2);
          printf("\n division of two numbers is %d",div);
          break;
       default:
          printf("select operations from one to four only");
          }
     getch();
     }             
output of add, subtract, multiply and divide operation using switch statement in C program



PRECAUTIONS

1. Use accurate header files.
2. Use word break after every single operation.
3. Always use ‘;’ after break in switch statement.
4. For output always use getch() and this function will execute with header file #include<conio.h>.
5. Always end the brackets if you taken into existence.

No comments:

Post a Comment