NIOS Computer Science: Chapter 9 – Control Statements Part 5

Download PDF of This Page (Size: 185K)

Image of switch case statement

Image of Switch Case Statement

Image of switch case statement

The execution of switch statement begins with the evaluation of expression.

If the value of expression matches with the constant then the statements following this statement execute sequentially till it executes break.

The break statement transfers control to the end of the switch statement.

If the value of expression does not match with any constant, the statement with default is executed.

Image of ‘switch’ statement

Image of ‘Switch’ Statement

Image of ‘switch’ statement

Example

# include < iostream.h>

void main ( )

{

char ch;

cout << "Enter a character";

cin >> ch;

switch (ch)

{

case 'a' : cout << "vowel a";

break ;

case 'e' : cout << "vowel e";

break ;

case 'o' : cout << "vowel o";

break ;

case 'i' : cout << "vowel i"

break ;

case ‘u’ : cout << “vowel u”;

break;

default : cout <<“not a vowel”;

}

}

The program needs the break statement to confine execution to particular portion of switch.

If the break statement is removed from the above program then it starts executing the statements associated with case labels specified till it comes across either the break statement or end of switch statement.

The above switch statement can be written as:

switch (ch)

{

case ‘a’ :

case ‘A’ : cout << “vowel a”;

case ‘e’ :

case ‘E’ : cout << “vowel e”;

case ‘i’ :

case ‘I’ : cout << “vowel i”;

break;

case ‘o’ :

case ‘O’ : cout << “vowel o”;

break;

default : cout << “not a vowel”;

}The input character either in small letter or capital will be accepted.