www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C Tutorial - Lesson 6: Conditional Processing, Part 2

Switch Statements and Logical Operators

by John Kopp

Support this site at no cost to you

Welcome to easyCPlusPlus.com's C tutorial. This second lesson on conditional processing introduces both the switch statement and logical operators. The switch statement is a construct that is used to replace deeply nested or chained if/else statements. Nested if/else statements arise when there are multiple alternative threads of execution based on some condition. Here's an example. Suppose that an ice cream store has asked us to write a program that will automate the taking of orders. We will need to present a menu and then based on the customer's choice take an appropriate action.

#include <stdio.h>

int main()
{
    int choice;

    printf("What flavor ice cream do want?\n");
    printf("Enter 1 for chocolate\n");
    printf("Enter 2 for vanilla\n");
    printf("Enter 3 for strawberry\n");
    printf("Enter 4 for green tea flavor, yuck\n");
    printf("Enter you choice: ");

    scanf("%d",&choice);

   if (choice == 1) {
        printf("Chocolate, good choice\n");
    }
    else if (choice == 2) {
        printf("Vanillarific\n");
    }
    else if (choice == 3) {
        printf("Berry Good\n");
    }
    else if (choice == 4) {
        printf("Big Mistake\n");
    }
    else {
       printf("We don't have any\n");
        printf("Make another selection \n");
    }

    return 0;
}

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()
{
    int choice;

    printf("What flavor ice cream do want?\n");
    printf("Enter 1 for chocolate\n");
    printf("Enter 2 for vanilla\n");
    printf("Enter 3 for strawberry\n");
    printf("Enter 4 for green tea flavor, yuck\n");
    printf("Enter you choice: \n");

    scanf("%d",&choice);

    switch (choice) {
    case 1:
        printf("Chocolate, good choice\n");
        break;
    case 2:
        printf("Vanillarific\n");
        break;
    case 3:
        printf("Berry Good\n");
        break;
    case 4:
        printf("Big Mistake\n");
        break;
    default:
        printf("We don't have any\n");
        printf("Make another selection\n");
    }

    return 0;
}
Previous Page       Next Page