The Switch Statement in C Language

The objective of Switch Statement in C Language is to check several possible constant values for an expression, something similar to the linking of several if and else if statements.

When the actions to be taken depending on the value of control variable, are large in number, then the use of control structure Nested if…else makes the program complex. There switch statement can be used.

The Syntax of The Switch Statement in C Language

switch (expression)
{
case expression 1:
block of instructions 1
break;
case expression 2:
block of instructions 2
break;
.
.
default:
default block of instructions
}

It works in the following way:

switch evaluates expression and checks if it is equivalent to expression1. If it is, it executes block of instructions 1 until it finds the break keyword, the moment it finds the control will go to the end of the switch.

If the expression was not equal to expression 1 it will check whether the expression is equivalent to expression 2. If it is, it will execute the block of instructions 2 until it finds the break keyword.

Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case statements as values you want to check), the program will execute the instructions included in the default: section, if it exists, as it is an optional statement.

A program to illustrate The Switch Statement in C Language

Write a program that performs the following, depending upon the choice selected by the user.

  • calculate the square of number if choice is 1
  • calculate the cube of number if choice is 2 and 4
  • calculate the cube of the given number if choice is 3
  • otherwise print the number as it is

Program

#include<stdio.h>

main()

{

int choice,n;

printf(“\n Enter any number:\n “);

scanf(“%d”,&n);

printf(“Choice is as follows:\n\n”);

printf(“1. To find square of the number\n”);

printf(“2. To find square-root of the number\n”);

printf(“3. To find cube of a number\n”);

printf(“4. To find the square-root of the number\n\n”);

printf(“Enter your choice:\n”);

scanf(“%d”,&choice);

switch (choice)

{

case 1 : printf(“The square of the number is %d\n”,n*n); break;

case 2 :

case 4 : printf(“The square-root of the given number is %f”,sqrt(n));

break;

case 3: printf(“ The cube of the given number is %d”,n*n*n);

default : printf(“The number you had given is %d”,n);

break;

}

}

OUTPUT

Enter any number:
4
Choice is as follows:
1. To find square of the number
2. To find square-root of the number\n);
3. To find cube of a number
4. To find the square-root of the number
Enter your choice:
2
The square-root of the given number is 2

 

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: