"Learn C programming!"

5-1 "switch ... case" structure

   

5-1 "switch ... case" structure

In previous lesson we saw how we can use "if" statement in programs that want to choose a way among several alternatives. 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 in case of each alternative
state.


Example 5-1:

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" 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.

After entering case portion, execution continues until it reaches a break statement.

"break" statements have vital rule in switch structure. If you remove these statements, program execution will continue to next case sections and all commands until the end of "switch" block will be executed.

As we told, This is because each 'case' acts exactly as a label. When program execution is transferred to a case
section it will continue running to the end of switch block. The only way to end execution of statements in switch block is using break statements at the end of each section.

In one of case sections we have not used "break". This is because we have used a termination command "exit(0)" and a break statement will not make sense.

"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) .

Using a variable in case sections is not allowed. This means that you are not allowed to use a statement like below in your switch block.

case i: something;
break;

-----------------------------------------------------------------------------

5-2 break statement

We used "break" statement in switch...case structures in previous part of lesson. We can also use "break" statement inside loops to terminate a loop and exit it.


Example 5-2:

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.

Example 5-3:

#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.

As a result of this change, we must use a second break statement inside while loop and outside switch block.

If the choice is 4 then this second break command will terminate while loop and we reach the end of main function and when there is no more statements left in main function program terminates automatically.

-----------------------------------------------------------------------------

5-3 getchar()

getchar() function is an alternative choice when you want to read characters from input. This function will get characters from input and return it to a variable or expression in our program.

ch=getchar();

There is a function for sending characters to output too.

putchar(ch);


Example 5-3:

#include<stdio.h>
#include<conio.h>
main()
{
char ch;

while(ch!='.')
{
ch=getchar();
putchar(ch);
}
}

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 captured 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 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.

Borland C for Dos as an example, supports this function and It is defined in conio.h header file in both Borland C and Turbo C compilers.

With this function we will be able to 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().


Look a this below example.

Example 5-4:

//code works on borland c
#include<stdio.h>
#include<stdlib.h>
#include<conio.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 invalid choices or string 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 .

If user presses an invalid key while loop will continue without entering any of "case" sections. So every invalid key press will be omitted and only valid key presses will be accepted.

-----------------------------------------------------------------------------

5-3 "continue" statement

Continue statement can be used in loops. Like break command "continue" changes flow of a program. While it does not terminate the loop.

It just skips the rest of current iteration of a loop and returns to start point of loop.


Example 5-5:

while((ch=getchar())!='\n')
{
if(ch=='.')
continue;
putchar(ch);
}

In above example, program accepts inputs and omits '.' character. If you run this example you will see that results will not appear until program execution is complete or in fact when enter key "\n" is pressed.

As we told later this delay is because getchar() function is a buffered input function.

-----------------------------------------------------------------------------

5-5 End

Once again we reach the end of our lesson. In next lesson we will work on more complex input/output functions. We will also see how we can write our own functions.

-----------------------------------------------------------------------------

Exercises:

 

1- Write a program that reads input until enter key is pressed ('\n' is found in input) and prints the number of alphabets and also number of spaces in input string. Use getchar() for reading input characters from console.

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.

============================================================

BreBru.Com Extra Information Technology HTML