Computer Concept & Programming In C - Unit II - 7

<action for choice 1>;
  break;
case <choice 2>:
<action for choice 2>;
 break;
default:
<action if choice does not match>;
 break;
}
To understand the difference between switch case and if-else statement, let us create a simple program in C Language which accepts a digit 1 through 7 ad print corresponding day of the week.
(i) By using if statement with else statement
# include <stdio.h>
# include <conio.h>
void main ( )
{
int C;
clrscr ( );
print f(“\n Enter a digit 1 through 7”);
scanf (“%d”, & c);
if ((c < 1) | | (c > 7))
printf(“\n Invalid”);
else
{
if (c = = 1)
printf(“\n Monday”);
if (c = = 2)
printf (“\n Tuesday”);
if (c = = 3)
printf(“\n Wednesday”);
if (c = = 4)
printf(“\n Thursday”);
if (c = = 5)
printf (“\n Friday”);
if (c = = 6)
printf (“\n Saturday”);
if (c = = 7)
printf(“\n Sunday”);
          }
getch ( );
                    }
(ii) Same program using switch case statement
                # include <stdio.h>
# include <conio.h>
void main ( )
{
int C;
clrscr ( );
print f(“\n Enter a digit 1 through 7”);
scanf (“%d”, & c);
switch (c)
               {
case 1 : printf(“\n Monday”);
break;
case 2 : printf (“\n Tuesday”);
break;
case 3 : printf (“\n Wednesday”);
break;
case 4 : printf (“\n Thursday”);
break;
case 5 : printf (“\n Friday”);
break;
case 6 : printf (“\n Saturday”);
break;
case 7 : printf (“\n Sunday”);
break;
default : printf(“\n Invalid”);
break;
                      }
getch ( );
                    }
Consider a case where a user input choice to both programs. The program made by using if-else statement will check all conditions thus a lot of time is wasted in checking unnecessary conditions where as the program made by using switch case statement just check a single condition and thus saves a lot of time.