20)

Program 19 - Switch and case

Program 19 Switch and case Source code - prog19.c
Program 19 shows how the switch and case statements can be used in place of 'if' statements. It was missed earlier, but is covered now by returning to the menu system example.

The program itself presents the user with four menu options. When the user selects any of the first three menu options the program displays which option they have pressed and waits for them to press a key to continue. If the user selects the 4th menu option ( to exit ) the program exits.

 

Program code- new parts shown in red

#include <stdio.h>
#include <conio.h>

void main(void)
{
unsigned char k;
int done=0
while(done==0)
{
clrscr();
printf("Menu\n\n");
printf("1 .. Option one\n");
printf("2 .. Option two\n");
printf("3 .. Option three\n");
printf("0 .. Exit\n\n");
printf("Please select an option from above\n\n");
k=getch();
switch(k)
{
case '1':
{
printf("You selected the first option .. press a key");
getch();
}
break;
case '2':
{
printf("You selected the second option .. press a key");
getch();
}
break;
case '3':
{
printf("You selected the third option .. press a key");
getch();
}
break;
case '0':done=1;break;
}
}
}

 

Description of the program code
The new parts of this program don't need a long explanation, most of it can be figured out.

The first new part of this program is the switch(k) line. The switch statement is always followed by a list of case statements inside a block. In the example above the value of the variable k is important in determining which case code block or line is executed.

If the value of the variable k is '1' ( 49 ) then the following is executed ( as signified by the use of case '1' : )

case '1':
{
printf("You selected the first option .. press a key");
getch();
}break;

A break; is always needed at the end of the line or code block in each case statement.

 

Summary
This small page and description contained information about the select and case statements, which can be used in place of if statements. The explanation is brief as the program code explains a lot better.

The next two programs look at how information can be stored in structures in memory.

 

Tasks

There are no tasks for this page.

 

Go back a page Continue on to next page >>

(c) J.C.Spooner 2001