LECTURE 8: More about Selection Statements (Chapter 4)

 

Coding Examples:

 

          Example 1:

 

       if (x == y)

       {

          printf ("x and y are equal\n");

       }

       else

       {

          printf ("x and y are NOT equal\n");

       }

 

           The condition (x == y) reads as "the value of x is EQUAL TO the value of y". This condition evaluates to TRUE if and only if x and y contain the same values.

 

                Example 2:

 

        if (x + y > 4)

        {

           printf ("x + y is greater than 4\n");

        }

        else

        {

           printf ("x + y is NOT greater than 4\n");

        }

 

            The condition (x + y > 4) reads as "the result of adding values of x and y is GREATER THAN 4". 

 

                How would you read the condition (x + (y > 4)), and how would you describe the result?

 

            How do we know the order of evaluation of expressions such as

         x + y > 4      x + y <= z*3     x + y && w + 3 != 16 * 2

                Answer:  We need to get familiar with the operator precedence chart.

 

 

  

         Example 3:

 

       if (x != 'D')

       {

          printf ("x is NOT equal to the character 'D'\n");

       }

       else

       {

          printf ("x is equal to the character 'D'\n");

       }

 

The condition (x != 'D') reads as "the value of x is NOT EQUAL TO the character 'D'".  This condition evaluates to TRUE if the value of x is the character 'R' which is NOT EQUAL TO the character 'D'.   Otherwise it evaluates to FALSE.

 

         Example 4:

 

(marital_status == ‘S’ && gender == ‘M’)

 

This expression evaluates to TRUE if the contents of marital_status is ‘S’ (for single) and if the contents of gender is ‘M’ (married).  Otherwise it evaluates to FALSE.  Note that if marital_status == S is FALSE (marital_status does not contain an S) the gender == ‘M’ evaluation will be short-circuited (not bothered with).  Once we know that any part of a logical expression involving && is FALSE, the entire expression must be FALSE. 

 

 The "switch" statement

 

         General form of the "switch" statement control structure:

 

         switch (expression)

         {

            case value1:

               /* Sequence of one or more dependent statements

                  executed when the expression is equal value1

               */

 

               dependent statement1;

               dependent statement2;

                  ...

               dependent statementN;

               break;

            case value2:

               /* Sequence of one or more dependent statements

                  executed when the expression is equal value2

               */

               dependent statement1;

               dependent statement2;

                  ...

               dependent statementN;

               break;

            case valueN:

               /* Sequence of one or more dependent statements

                  executed when the expression is equal valueN

               */

 

               dependent statement1;

               dependent statement2;

                  ...

               dependent statementN;

               break;

                          default:

               /* Sequence of one or more dependent statements

                  executed when the expression none of the values

                  value1, value2, … valueN is equal to the

                  expression.

               */

               dependent statement1;

               dependent statement2;

                  ...

               dependent statementN;

               break;

         }

 

"expression" (called the controlling expression) can be any integer –valued or character-valued expression and the values (value1 … valueN) are integer or character values to which the expression is compared. 

 

The expression that you "switch" on must evaluate to either an integer OR a character value.  The resulting value is compared to the value in each of the case statements until a matching case value is found. Once a matching case value has been found no more comparisons take place and the remaining case statements are in effect ignored.  The switch statement executes the appropriate dependent statements until the switch statement has finished executing.

 

Note that is a break statement is omitted at the end of any set of dependent   statements, then all dependent statements following the first matching case statement are executed one after another until EITHER a

 i)  another break statement is reached or

ii) the end of the switch statement is reached,

  

which ever comes first.  The break causes the program execution to "break" out of the switch statement and transfer control to the first executable statement that occurs after the end of the switch statement.  This causes the remainder of the switch statement to be skipped.  The end of the switch statement is defined as the closing curly brace on the switch statement.

 

 

 

Example:

 

     int main()

     {

         char grade;   // Hold a letter grade entered by a user

 

         /* Get the letter grade from the user */

         printf ("Enter the student's grade > ");

         scanf ("%c", &grade);

 

         /* Display the appropriate message by "switch"ing on the 

         /* letter grade entered by the user                      

 

         /* Compare the value of the variable grade to the each

            of the cases until it matches a case.  Once you have

            matched a case, no other attempts are made to match

            any more cases.  At this point, the computer executes

            the dependent statements for the matched case until

            a break is encountered or the end of the switch is

            encountered, which ever comes first.

         */

 

         switch (grade)

         {

            case 'A': // if grade matches case 'A', continue here

            case 'a'    // if grade matches case 'A', continue here

                printf ("%c = Excellent\n", grade);

                break;

            case 'B': // if grade matches case 'B', continue here

            case 'b': // if grade matches case ‘b’, continue here

                printf ("%c = Good\n", grade);

                break;

            case 'C': // if grade matches case 'C', continue here

            case 'c': // if grade matches case ‘c’, continue here

                printf ("%c = Average\n", grade);

                break;

            case 'D': // if grade matches case 'D', continue here

            case 'd': // if grade matches case 'd', continue here

                printf ("%c = Below Average\n", grade);

                break;

            case 'F': // if grade matches case 'F', continue here

            case 'f': // if grade matches case 'f', continue here

                printf ("%c = Failing\n", grade);

                break;

            default:

                /* The only way to reach here is if grade did NOT

                   match any of the cases 'A', 'a', 'B', 'b',

                   'C', 'c', 'D', 'd', 'F' or 'f'.

                */

                printf ("Invalid grade entered - %c\n", grade);

        } // end of switch

     }    // end of main

 

Common Programming Errors (Section 4.9)

 

Example 1

if (0 <= x <= 4)

printf(“x is between 0 and 4 inclusive”);

Explanation: Assume x equals 10. The condition is evaluated from left to right. Then, the value of 0 <= x is 1 (TRUE). Then, the value of 1 <=4 is 1 (TRUE), and the whole condition 0 <= x <= 4 is evaluated as TRUE! The right way to write the condition is (0 <= x && x <= 4).

 

Example 2

if(x = 10)

printf(“x is 10”);

Explanation: meaning of (x = 10) is to assign value 10 to x. The value of (x = 10) is 10, which is TRUE (remember, every nonzero value is interpreted as TRUE). Therefore, “x is 10” is always printed, regardless of the initial value of x. The right way to write the condition is (x == 0).

 

Example 3

if(x > 0)

sum = sum + x;

printf(“Greater than zero”)

else

printf(“Less or equal to zero”);

Explanation: We forgot to use braces after if. So, after sum = sum + x is executed the computer will assume we are out of if-else statement. Then, printf will be executed, and when else is encountered the computer will be confused (since there is always if before else) and program will have a syntax error.