Selection It is often the case that depending upon the value of an expression

Selection it is often the case that depending upon

This preview shows page 31 - 44 out of 64 pages.

Selection It is often the case that depending upon the value of an expression we want to perform a particular action Two major ways of accomplishing this choice if-else-if statement if-else statements “glued” together switch statement An advanced construct
Image of page 31
An if-else-if Statement if ( nbr < 0 ) { cout << nbr << " is negative" << endl; } else if ( nbr > 0 ) { cout << nbr << " is positive" << endl; } else { cout << nbr << " is zero" << endl; }
Image of page 32
A switch Statement switch ( SwitchExpression ) { case CaseExpression 1 : Action 1 ; break ; case CaseExpression 2 : Action 2 ; break ; ...... case CaseExpression N : Action N ; break ; default: Default action ; } The case expression must be constant integral expression Actions are either a single statement or a group of statements
Image of page 33
A switch Statement Example: 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; }
Image of page 34
cout << "Enter simple expression: "; int iLeft; int iRight; char chOperator; cin >> iLeft >> chOperator >> iRight; cout << iLeft << " " << chOperator << " " << iRight << " = "; switch (chOperator) { case '+' : cout << iLeft + iRight << endl; break; case '-' : cout << iLeft - iRight << endl; break; case '*' : cout << iLeft * iRight << endl; break; case '/' : cout << iLeft / iRight << endl; break; default: cout << "Illegal operation" << endl; }
Image of page 35