Selection using Switch Statements
In previous lesson we saw how we can use "if"
statement in programs when they need to choose an option from among several
alternatives. There is an alternative C programming command which in some
cases can be used as an alternate way to do this. “Switch…case” command is more
readable and easier language structure.
"Switch ... case" structure
We can use "if"
statement yet but it is better to use "switch" statement which is
created for situations that there are several choices.
switch(...)
{
case ... : command;
command;
break;
case ... : command;
break;
default:
command;
}
In the above switch command
we will be able to run different series of commands with each different case.
Example 5-1: example5-1.c
Rewrite example 4-5 of
previous lesson and use switch command instead of "if" statement.
#include<stdio.h>
#include<stdlib.h>
main()
{
int choice;
while(1)
{
printf("\n\nMenu:\n");
printf("1- Math Program\n2-
Accounting Program\n");
printf("3- Entertainment
Program\n4- Exit");
printf("\n\nYour choice ->
");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("\nMath Program
Runs. !");
break;
case 2 : printf("\nAccounting
Program Runs. !");
break;
case 3 :
printf("\nEntertainment Program Runs. !");
break;
case 4 : printf("\nProgram
Ends. !");
exit(0);
default:
printf("\nInvalid
choice");
}
}
}
In "switch…case" command, each “case” acts
like a simple label. A label determines a point in program which execution must
continue from there. Switch statement will choose one of “case” sections or
labels from where the execution of the program will continue. The program will
continue execution until it reaches “break” command.
"break" statements have vital rule in switch
structure. If you remove these statements, program execution will continue to
next case sections and all remaining case sections until the end of
"switch" block will be executed (while most of the time we just want
one “case” section to be run).
As we told, this is because each “case” acts just as a
label. The only way to end execution in switch block is using break statements
at the end of each “case” section.
In one of case sections we have not used
"break". This is because we have used a termination command
"exit(0)" (which terminates program execution) and a break statement
will not make any difference.
"default" section will be executed if none
of the case sections match switch comparison.
Parameter inside “switch” statement must be of type “int
or char” while using a variable in “case sections” is not allowed at all. This
means that you are not allowed to use a statement like below one in your switch
block.
case i: something;
break;
Break statement
We used "break"
statement in “switch...case” structures in previous part of this lesson. We can
also use "break" statement inside loops to terminate a loop and exit
it (with a specific condition).
Example 5-2: example5-2.c
while (num<20)
{
printf("Enter score : ");
scanf("%d",&scores[num]);
if(scores[num]<0)
break;
}
In above example loop execution continues until either num>=20 or entered
score is negative. Now see another example.
Example 5-3: example5-3.c
#include<stdio.h>
#include<stdlib.h>
main()
{
int choice;
while(1)
{
printf("\n\nMenu:\n");
printf("1- Math Program\n2- Accounting
Program\n");
printf("3- Entertainment
Program\n4- Exit");
printf("\n\nYour choice ->
");
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("\nMath Program
Runs. !");
break;
case 2 : printf("\nAccounting
Program Runs. !");
break;
case 3 :
printf("\nEntertainment Program Runs. !");
break;
case 4 : printf("\nProgram
Ends. !");
break;
default:
printf("\nInvalid
choice");
}
if(choice==4) break;
}
}
In above example we have used
a break statement instead of exit command used in previous example. Because of this change, we needed a second break
statement inside while loop and outside switch block.
If the choice is 4 then this second “break command”
will break while loop and we reach the end of main function and when there is
no more statements left in main function program terminates automatically.
getchar() and getch()
getchar() function is an
alternative choice when you want to read characters from input. This function
will get single characters from input and return it back to a variable or
expression in our program.
ch=getchar();
There is a function for
sending characters to output too.
putchar(ch);
Example 5-4: example5-4.c
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
while(ch!='.')
{
ch=getchar();
putchar(ch);
}
system("pause");
}
First look at output results
and try to guess the reason for results. Console Screen:
test <--This is typed by us
test <--output of putchar
after we pressed enter
again.testing <--Typed string
includes a '.' character
again. <--Loop terminates
when it reaches '.' char
Above program reads any character that you have typed
on keyboard until it finds a '.' character in input characters. Each key press
will be both shown on console and added to a buffer. This buffer will be
delivered to 'ch' variable after pressing enter key (not before this). So input
characters are buffered until we press enter key and at that moment program
execution continues running statements that follow getchar() function (These
are loop statements).
If there is a '.' character in buffered characters,
loop execution continues sending characters to console with putchar() function
until it reaches '.' and after that stops the loop and comes out of while
loop.
If it does not encounter '.'
in characters it returns to the start of loop, where it starts getchar()
function again and waits for user input.
First 'test' string appeared in
output is the result of our key presses and second 'test' is printed by putchar
statement after pressing enter key.
In some operating systems and some C Programming
language compilers, there is another character input function
"getch". This one does not buffer input characters and delivers them
as soon as it receives them. (in Borland C you need to include another header
file <conio.h> to make this new function work).
Example 5-5: example5-5.c
#include<stdio.h>
main()
{
char ch;
while(ch!='.')
{
ch=getch();
putch(ch);
}
system("pause");
}
Testing. <--program terminates
immediately after we use the
character ‘.', also
characters are sent to output once
With this function we can also check
validity of each key press before accepting and using it. If it is not valid we
can omit it. Just pay attention that some compilers do not support getch(). (Again
Borland c needs the header file conio.h to be included)
Look at below example.
Example 5-6: example5-6.c
#include<stdio.h>
#include<stdlib.h>
main()
{
char choice;
while(1)
{
printf("\n\nMenu:\n");
printf("1- Math Program\n2-
Accounting Program\n");
printf("3- Entertainment
Program\n4- Exit");
printf("\n\nYour choice ->
");
choice=getch();
switch(choice)
{
case '1' : printf("\nMath
Program Runs. !");
break;
case '2' : printf("\nAccounting
Program Runs. !");
break;
case '3' :
printf("\nEntertainment Program Runs. !");
break;
case '4' : printf("\nProgram
Ends. !");
exit(0);
}
}
}
In above example we have rewritten example 5-1. This
time we have used getch() function instead of scanf() function. If you test
scanf based example you will see that it does not have any control on entered
answer string. If user inserts an invalid choice or string (a long junk string
for example), it can corrupt the screen. In getch function, user can insert one
character at a time. Program immediately gets the character and tests it to see
if it matches one of the choices.
In this example we have omitted optional
"default" section in “switch...case”. Pay careful attention that in
scanf based example we used to get an integer number as the user choice while
here we get a character input. As a result previously we were using integer
variable in “switch section” and integer numbers in “case sections”. Here we
need to change the “switch … case” to match the character type data. So our
switch variable is of char type and values being compared are used like '1', '2', '3', '4' because they are character type data ('1'
character is different from the integer value 1).
If user presses an invalid key while loop will
continue without entering any of "case" sections. Invalid key press
will be omitted and only valid key presses will be accepted.
"continue" statement
Continue statement can be used in loops. Like break
command "continue" changes flow of a program. It does not terminate
the loop however. It just skips the rest of current iteration of the loop and
returns to starting point of the loop.
Example 5-7: example5-7.c
#include<stdio.h>
main()
{
while((ch=getchar())!='\n')
{
if(ch=='.')
continue;
putchar(ch);
}
system("pause");
}
In above example, program accepts all input but omits the
'.' character from it. The text will be echoed as you enter it but the main
output will be printed after you press the enter key (which is equal to
inserting a "\n" character) is pressed. As we told earlier this is
because getchar() function is a buffered input function.
Exercises
1. Write a program that reads input until enter key is pressed ('\n' is found in input) and prints number of alphabets and number of spaces in the input string. Use getchar() for reading input characters from console. ( example output: alphabet: 34 spaces: 10 )
2. Write a program that reads input and replaces below characters with the character that comes in front of them. Then writes the output on your screen.
a -> c
f -> g
n -> l
k -> r
Use getchar() and switch...case to write the program.
Next Lesson
|