Presentation is loading. Please wait.

Presentation is loading. Please wait.

The switch Statement When we want to compare a variable against several values to see which one it has, we can use the switch statement: switch (status)

Similar presentations


Presentation on theme: "The switch Statement When we want to compare a variable against several values to see which one it has, we can use the switch statement: switch (status)"— Presentation transcript:

1

2 The switch Statement When we want to compare a variable against several values to see which one it has, we can use the switch statement: switch (status) { case 0: // single case goes here break; case 1: // married joint goes here case 2: // married single goes here case 3: // head-of-household goes here default: // invalid status goes here }

3 §3.15 The switch Statement The flowchart version of the switch statement:

4 The rules for using switch:
The expression must be a char, byte, short, or int (no long, float, double, or String), and it must go in parentheses The values in the case clauses must be of the same type as the switch expression, and must be constants Java and C++ check the case values in order. Once it finds a match, it keeps executing code until it sees either break or the end of the switch statement

5 The rules for using switch:
Be aware of the need for break! switch (ch) // assume ch is 'a' { case 'a': System.out.print('a'); case 'b': System.out.print('b'); case 'c': System.out.print('c'); } This outputs "abc". Without a break to end each case, execution "falls through" to the next case.

6 The rules for using switch:
Be aware of the need for break! switch (ch) // assume ch is 'a' { case 'a': System.out.print('a'); break; case 'b': System.out.print('b'); break; case 'c': System.out.print('c'); break; } This outputs "a"

7 A Switch Statement switch (ch) { case 'a': case 'A':
case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': cout << ch << " is a vowel" << endl; break; default: cout << ch << " is not a vowel" << endl; }

8 int Left; int Right; char Operator; cout << "Enter simple expression: "; cin >> Left >> Operator >> Right; cout << Left << " " << Operator << " " << Right << " = "; switch (Operator) { case '+' : cout << Left + Right << endl; break; case '-' : cout << Left - Right << endl; break; case '*' : cout << Left * Right << endl; break; case '/' : cout << Left / Right << endl; break; default: cout << "Illegal operation" << endl; }


Download ppt "The switch Statement When we want to compare a variable against several values to see which one it has, we can use the switch statement: switch (status)"

Similar presentations


Ads by Google