switch in c programing

how to use switch blocks in c, decision making in c with switch statement


Category: C Programming Tags: C Programming


switch with c :

        Today i am going to show you how to use switch in c programing for decision making and branching of our program.Let's have a look of program below:
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int num=0;
printf("\nenter 1 for male and 2 for female and 3 for exit:\n");
scanf("%d",&num);
switch(num)
{
case 1:
printf("you entered male");
break;
case 2:
printf("you entered female");
break;
case 3:
printf("press any key for exit");
break;
default :
printf("please enter only 1 or 2\a");
return main();
}
getch();
}

#include :- directive tells the pre-processor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears.

stdio.h :- . The stdio header provides functions for performing input and output.like printf for output and scanf for input on console.these files used with #include<filename> and called header files.

conio.h :- Conio.h is a header file which have functions declaration. One of them is clrscr() function. This function have its prototype in conio.h. clrscr() function is used to clear the screen. and getch() for take a input.

printf :- for print a line on console

scanf :- set inputs to a declared variable.in above program it would take input from user and set that input to num.

switch :- for decision making and branching.it takes one argument in above program i is having num as input and i have 4 cases . where first 3 is for num value 1,2,3. if any one enter 1,2 or 3 then any one of case 1, case 2, case 3 would execute else in any other value default case would execute.in default case we called main again because if user enters any other number instead of 1,2,3 then program would not exit and he have to enter 3 foe exit.

getch :- would execute in last and make program alive till user press any key. then user would be able to see results it that time.


Output :-
enter 1 for male and 2 for female and 3 for exit:
1
you entered male.

Like 1 Person
Published on 3 September 2013
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 158
Questions: 16
Given Best Solutions: 16 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x