switch case statement in C, sample programs, programs to try

Switch Statement in C

There is one potential problem with the if–else statement: the complexity of the program increases as the number of alternative paths grows.
Using multiple if–else constructs can make a program difficult to read and understand, and sometimes it may even confuse the developer who wrote it.

Solution

The solution to this problem is the switch statement.


Definition

A switch statement is used for multiple-way selection, branching into different code segments based on the value of a variable or expression.
This expression or variable must be of integer type.


Syntax

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

Explanation

  • The value of the expression may be:

    • Generated during program execution, or

    • Read as user input.

  • The expression can be of type int, char, or enum.

  • The case whose value matches the expression is selected and executed.

  • The default label is optional and runs when no case matches.

  • The position of the default block 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 evaluate to a result.

  • Case labels must be constants and unique.

  • Each case label must end with a colon (:).

  • A break keyword should be present in each case.

  • There can be only one default label.

  • Multiple switch statements can be nested.


Summary

  • A switch is a decision-making construct in C.

  • It is used in programs where multiple decisions are involved.

  • A switch must contain an executable test expression.

  • Each case should include a break statement.

  • Case labels must be constant and unique.

  • The default case 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.

  • If you need to select among a large group of values, a switch statement usually runs faster than nested if statements.

  • The switch statement can only test for equality, while if can evaluate any Boolean expression.

  • Switch statements are commonly 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

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays