Switch Case Operations
Today I want to write about switch-case statement in c. This statement is a totaly saver in some situation. However, It has a tricky point and before using that you should learn that tricky point.
I want to explain it with an example code :
#include <stdio.h>
main()
{
int Grade = 'A';
switch( Grade )
{
case 'A' : printf( "Perfect\n" );
case 'B' : printf( "Good\n" );
case 'C' : printf( "OK\n" );
case 'D' : printf( "Danger\n" );
case 'F' : printf( "Problem\n" );
default : printf( "You Did a Mistake\n" );
}
}
if we write the program like this , our output will become like this.
Perfect
Good
OK
Danger
Problem
You Did a Mistake
So we should use break statement between two cases to solve the
problem.
#include <stdio.h>
main()
{
int Grade = 'A';
switch( Grade )
{
case 'A' : printf( "Perfect\n" );
break;
case 'B' : printf( "Good\n" );
break;
case 'C' : printf( "OK\n" );
break;
case 'D' : printf( "Danger\n" );
break;
case 'F' : printf( "Problem\n" );
break;
default : printf( "You Did a Mistake\n" );
break;
}
}
This time our output will become
Perfect
Break point is very important while using the swich-case statement.
Default cases do the same work as else.
Comments
Post a Comment