Skip to main content

switch statement in C,sample programs and programs to try

There is one potential problem with the if-else statement which is the complexity of the program increases whenever the number of alternative path increases. If you use multiple if-else constructs in the program, a program might become difficult to read and comprehend. Sometimes it may even confuse the developer who himself wrote the program.

The solution to this problem is the switch statement.

A switch statement is used for multiple way selections that will branch into different code segments based on the value of a variable or expression. This expression or variable must be of integer data type.

Syntax:
switch (expression)
{
case value1:
                  code segment1;
                  break;
case value2:
                 code segment2;
                 break;
case valueN:
                 code segmentN;
                 break;
default:
                default code segment;
}

The value of this expression is either generated during program execution or read in as user input.The expression can be  int, char or enum.
The case whose value is the same as that of the expression is selected and executed. The optional default label is used to specify the code segment to be executed when the value of the expression does not match with any of the case values.The position of the default does not matter.
 


Examples:
Checking even or odd number
 #include <stdio.h> 
int main() 
int number; 
printf("Enter a number \n");
scanf("%d",&number);
switch(number%2)
{
case 0:printf("even\n");
           break;
case 1:printf("odd\n");
           break;
}
}
check whether the number is +ve -ve or 0 ( University Question)
#include <stdio.h>
#include <math.h>

int main() {
    int num, sign;
    
    printf("Enter a number: ");
    scanf("%d", &num);
    
    sign = (num > 0) - (num < 0);
    
    switch (sign) {
        case 1:
            printf("Positive number\n");
            break;
        case 0:
            printf("Zero\n");
            break;
        case -1:
            printf("Negative number\n");
            break;
    }
    
    return 0;
}


checking divisibility by 3
#include <stdio.h> 
int main() 
int number; 
printf("Enter a number \n");
scanf("%d",&number);
switch(number%3)
{
case 0:printf("Divisible by 3\n");
           break;
default:printf("Not divisible by 3\n");
           break;
}
}
The break statement is present at the end of every case. If it were not so, the execution would continue on into the code segment of the next case without even checking the case value.
Example:
#include <stdio.h> 
int main() { 
int number; 
printf("Enter a +ve number \n");
scanf("%d",&number);
switch (number) 
case 1: 
case 2: 
case 3: 
    printf("One, Two, or Three.\n"); 
    break; 
case 4: 
case 5: 
case 6: 
    printf("Four, Five, or Six.\n");
     break; 
default: printf("Greater than Six.\n");
}
}
We can also nest switch statement.ie; we can include one switch statement within another.
#include <stdio.h> 
int main() 
 int ID; 
int password; 
printf("Plese Enter Your ID:\n "); 
scanf("%d", & ID); 
 switch (ID) 
{ case 500: 
                printf("Enter your password:\n "); 
                scanf("%d", & password); 
                switch (password) 
                
                case 000: printf("Welcome Dear Programmer\n"); 
                                break; 
                default: printf("incorrect password"); 
                               break; 
                
                break; 
     default: 
            printf("incorrect ID"); 
            break; 
         } 
}

GNU gcc compiler also support to specify range of values to be mentioned in case.
Example:
#include <stdio.h>
int main()
{
    int m;
    printf("Enter Mark out of 100....m\n");
    scanf("%d",&m);
    switch(m)
    {
     case 0 ... 39:printf("Failed \n") ; 
                break;
    case 40 ... 100:printf("Passed \n")  ;
                break;
    }
    return 0;
}
 
Rules for switch statement:

An expression must always execute to a result.
Case labels must be constants and unique.
Case labels must end with a colon ( : ).
A break keyword must be present in each case.
There can be only one default label.
We can nest multiple switch statements.
Summary
A switch is a decision making construct in 'C.'
A switch is used in a program where multiple decisions are involved.
A switch must contain an executable test-expression.
Each case must include a break keyword.
Case label must be constants and unique.
The default is optional.
Multiple switch statements can be nested within one another.
  
Note:
All programs written using the switch-case statement can also be written using the if-else statement.However, If you need to select among a large group of values, a switch statement will run much faster than a set of nested ifs. The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression.The switch statement must be used when one needs to make a choice from a given set of choices. The switch case statement is generally used in menu-based applications.
 
Example Programs: 
Program to print the day of the week.
 #include<stdio.h>

int main( )
{
int day;
printf("\nEnter the number of the day:");
scanf("%d",&day);
switch(day)
{
case 1: printf("Sunday");
            break;
case 2:
            printf("Monday");
            break;
case 3:
            printf("Tuesday");
            break;
case 4:
            printf("Wednesday");
            break;
case 5:
            printf("Thursday");
            break;
case 6:
            printf("Friday");
            break;
case 7:
            printf("Saturday");
            break;
default:
            printf("Invalid choice");
}
return 0;
}

Menu driven program using switch.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
main()
{     
  int ch;
  float r,b,h,arc,art;                               
  system("clear");
  printf("Menu\n");
  printf("1.area of the circle\n");
  printf("2.area of the triangle\n");
  printf("3.exit\n");
  printf("enter your choice\n");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1:printf("Enter radius\n");
          scanf("%f",&r);
          arc=3.14*r*r;
          printf("Area of the circle=%f\n",arc);
          break;
   case 2:
          printf("Enter base and height\n");
          scanf("%f%f",&b,&h);
          art=0.5*b*h;
          printf("Area of the triangle=%f\n",art);
          break;
    case 3:
           printf("Bye\n");
           exit(0);  

     default:
         printf("invalid option\n");
  }
}

Reading grade and printing Good (o,a,b) or Bad (any other)

#include <stdio.h>
main()

  char grade;
    scanf("%c",&grade);
   switch(g)
   {
   case 'o':
   case 'a':
   case 'b':printf("Good\n");
            break;
    default:
         printf("Bad\n");
   }

}

Program to find all roots of a quadratic equation using switch case 

#include <stdio.h>
#include <math.h>
int main() {
float a, b, c; float root1, root2, imaginary;
float discriminant;
printf("Enter values of a, b, c of quadratic equation (aX^2 + bX + c): ");
scanf("%f%f%f", &a, &b, &c);

/* Calculate discriminant */
discriminant = (b * b) - (4 * a * c);

/* Compute roots of quadratic equation based on the nature of discriminant */
switch(discriminant > 0) {

case 1: /* If discriminant is positive */
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        printf("Two distinct and real roots exists: %.2f and %.2f", root1, root2);

        break;

case 0: /* If discriminant is not positive */

            switch(discriminant < 0)

            { case 1: /* If discriminant is negative */
                    root1 = root2 = -b / (2 * a);
                    imaginary = sqrt(-discriminant) / (2 * a);
                    printf("Two distinct complex roots exists: %.2f + i%.2f and %.2f - i%.2f", root1, imaginary,                         root2, imaginary);

                break;

                case 0: /* If discriminant is zero */
                        root1 = root2 = -b / (2 * a);
                        printf("Two equal and real roots exists: %.2f and %.2f", root1, root2);
                        break;
}
}
return 0;
}

 Programs to try

1.Print the month name corresponds to the month number and also print the number of days.Read month number.

2.Check whether the given number is odd or even

3.Read a character.If it is 'P' print Python.If it is 'J' print java.Print invalid character if it is any other character.

4.Read a character and Check for vowel.

5.Create a simple calculator( +,-,*,/).Read the operator and two numbers and do the operation based on the operation.

6.Write a menu driven program to compute area of a circle (option 1) or area of a triangle ( option 2) using switch statement.

7.Write a switch statement that will examine the value of a char-type variable called color and print one of the following messages, depending on the character assigned to color.

(a) RED, if either r or R is assigned to color,
(b) GREEN, if either g or G is assigned to color,
(c) BLUE, if either b or B is assigned to color,
(d) BLACK, if color is assigned any other character.
 
8.Find the roots of a quadratic equation.

Comments

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar