learnprogramming123

LEARN PROGRAMMING 123
your resources to programming and free tutition



Navigation

 
C
 
C++ soon here!

Search

 

 

 

 

Next Back

 

Lesson 7: The switch statement and logical operators

This lesson will show you how to:

  • Test for multiple conditions using the switch statement
  • What is the default in the switch statement
  • Use of break() in the switch statement
  • Use of logical operators in the if.... else.... constructs

    Q. How do you know when a blonde has an orgasm?
    A. She drops her bag of chips.

The switch statement is a construct that is used when many conditions are being tested for. When there are many conditions, it becomes too difficult and complicated to use the if and else if constructs. Nested if/else statements arise when there are multiple alternative paths of execution based on some condition that is being tested for. Here's an example, this is a simple calculator that can be used to add, multiply, subtract, and divide. If this program was using if else statements than this program will work fine, but the if/else block is cumbersome. It would be easy, particularly if there were more choices and maybe sub choices involving more if/else's to end up with program that doesn't perform the actions intended. Here's the same program with a switch.

#include <stdio.h>

int main(void)
{
    float numb1 = 0, numb2 = 0;       /* the two numbers to work on */
    int menu = 1;             /* add or substract or divide or multiply */
    float total = 0;           /* the result of the calculation */
    char calType;             /* what type of calculation */

    printf("Please enter in the first of the two numbers\n\t");
    scanf("%f", &numb1);                 /* READ first number */

    printf("\n\nPlease enter the second of the two numbers\n\t");
    scanf("%f", &numb2);                 /* READ second number */

    printf("\n\nWhat would you like to do?\n\n");    /* WRITE instructions */
    printf("\t1 = add\n");
    printf("\t2 = substract\n");
    printf("\t3 = multiply\n");
    printf("\t4 = divide\n");

    printf("\n\nPleas make your selection now:\n\t");
    scanf("%d",&menu);                   /* READ calculation type */

    switch (menu)                  /* select the type of calculation */
    {
    case 1: total = numb1 + numb2;
        calType = '+';             /* assign a char to symbolise calculation type */
        break;
    case 2: total = numb1 - numb2;
        calType = '-';
        break;
    case 3: total = numb1 * numb2;
        calType = '*';
        break;
    case 4: total = numb1 / numb2;
        calType = '/';
        break;
    default: printf("Invalid option selected\n");
    }

    if (menu == 3 && numb2 == 0)            /* cannot divide by 0 */
        printf("\n\n\tYou cannot divide by 0\n\n");

              /* display result to 2 decimal places */
    printf("\n\n*************************");
    printf("\n\n\t%.3f %c %.3f = %.2f", numb1, calType, numb2, total);
    printf("\n\n*************************\n\n");

    return 0;

}

    The keyword default is executed when none of the conditions being tested for in the switch statement are met or executed. The break statement must be used after each condition because if it were not used than all the conditions from the one met will be executed. For example if case 2 was met, and there was no break statement at the end of the case, case 3 and case 4 and even default would all be executed.

    The general form of a switch statement is:

    switch (variable) {
    case expression1:
    do something 1;
    break;
    case expression2:
    do something 2;
    break;
    ....
    default:
    do default processing;
    }

    Logical Operators

    In more realistic examples, it is probably necessary to evaluate multiple conditions to determine what parts of code should execute. For instance, if condition 1 is true and condition 2 is true process one way, if condition 1 is true and condition two is false process another way. C provides several logical operators that allow more complex relational expressions to be formed and evaluated.

    Operator Description Example Evaluation
           
    && AND (5 > 1) && (3>10) False
    && AND (2 >1) && (10 > 9) True
    || OR (3> 1) || (10 > 11) True
    || OR (4> 2) || (10 > 5) True
    ! NOT !(5>1) False
    ! NOT !(2 > 3) True
           

As can be seen in this table, && will return true only if both expressions are true, while || will be true if either expression is true. The operator "!" provides logical negation. One very important consideration when forming expressions is the order of precedence (what is executed when) of the relational and logical operators. Relational operators are of higher precedence (they are executed first) than the logical and the order of evaluation is from left to right. Here are some examples that illustrate what this means.

if (myChoice == 'A' and myAge < 25) is evaluated as
if ((myChoice == 'A') and (myAge < 25))

Suppose x = 8, y = 49, z = 1.
if (x < 7 && y > 50 || z < 2) is evaluated as
if (((x < 7) && (y > 50)) || (z < 2)) which is TRUE, not as
if ((x < 7) && ((y > 50) || (z < 2)) which is FALSE.

Now, here are a few final points to wrap up this lesson. First, even if you are sure about the order of precedence of an expression, use many parenthesis (just in case). This serves to increase readability and will help avoid errors. Second, there is such a thing as green tea ice cream and I recommend that you not buy it.

back to top        go to next lesson


 


 






Hosted by www.Geocities.ws

1