Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

C programming - The switch construct in C

August 13, 2013 Posted by: GPA Views: 691 0 comments

Switch is the control statement in c which controls the program and helps select conditions. It works same as If-Else Selection Statement. The difference between Switch and If-Else Selection Statement that switch is used for reduce the if statements. If we use the multiple choices better for this use Switch control. It is easier than the If-Else construct. Switch control checks the choice value and go to specific case label if the case exists else it go to the default label.

The preceding pseudocode Switchmay be written in C as:

switch (choice) {
       case this-choice:
                do something
               break;
       case that-choice:
             do something
           break;
            ...
        default:
            do something
        break;
 

In example you will see that how to use the switch statement. The program take a number and check if the number lies between 1 to 4. If user entered the number between 1 to 4 then program print selected menu item. Else it prints "You have not selected menu item".

Example:

   
       
#include
<stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
   int ch=0;//variable for choice
printf("Main menu\n");
   printf("1- menu item 1\n");
   printf("2- menu item 2\n");
   printf("3- menu item 3\n");
   printf("4- exit\n");
   printf("Select one menu item: ");
   scanf("%d",&ch);//read user choice
   //switch control statement
   switch(ch){
       case 1:
            printf("You have selected menu item 1\n");
              break;
case 2:
            printf("You have selected menu item 2\n");
             break;
       case 3:
            printf("You have selected menu item 3\n");
           break;
       case 4:
            exit(0);
            break;
           default:
           printf("You have not selected menu item\n");
         break;
  }  
   system("PAUSE");  
  return 0;
}

Output

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe