C switch statement

Consider a situation in which we have many options out of which we need to select only one option that is to be executed. Such kind of problems can be solved using nested if statement. But as the number of options increases, the complexity of the program also gets increased. This type of problem can be solved very easily using a switch statement. Using the switch statement, one can select only one option from more number of options very easily. 

Functioning of switch case statement

First, the integer expression specified in the switch statement is evaluated. This value is then matched one by one with the constant values given in the different cases. If a match is found, then all the statements specified in that case are executed along with the all the cases present after that case including the default statement. No two cases can have similar values. If the matched case contains a break statement, then all the cases present after that will be skipped, and the control comes out of the switch. Otherwise, all the cases following the matched case will be executed.

Syntax:

switch (expression)
{
case value 1 :
statement block 1;
break;
case value 2:
statement block 2;
break;
:
:
default:
default block;
}
statement n;
 
Example
 
To calculate the area of a rectangle or circle or triangle by taking the user’s choice.
 
#include<stdio.h>
#include<conio.h>

void main()
{
int ac,ar,at,r,l,b,ba,h,choice;

   printf("\n\n*********Main Menu*********\n");  
    printf("\nChoose one option from the following list ...\n");
    printf("\n1.Area of circle\n2.Area of rectangle\n3.Area of triangle\n4.Exit\n");
     printf("Enter your choice\n");
    scanf("\n %d",&choice);

    switch(choice)
    {
    case 1:
        printf("\n Enter radius: ");
        scanf("%d",&r);
        ac=3.14*3.14*r;
        printf("Area of circle is: %d",ac);
        break;
    case 2:
        printf("\n Enter length and breadth:");
        scanf("%d %d",&l,&b);
        ar=l*b;
        printf("Area of rectangle is: %d",ar);
        break;
    case 3:
        printf("\n Enter base and height: ");
        scanf("%d %d",&ba,&h);
        at=0.5*ba*h;
        printf("Area of triangle is: %d",at);
        break;
    }
getch();
}
 
Output
 

 

 

 

 

 



No comments:

Post a Comment