More Than Two Paths

Sometimes the type of decision that we need to make involves choosing between more than 2 things. For example, the decision on how to get from one place to another could involve choosing between, driving, taking public transit, riding a bike, or walking. In programming similar decision problems exists. Thus we need a mechanism that allows us to choose between 3 or more pathways.

Problem #2

In Toronto, Ontario, the Toronto Transit Commission (TTC) charges $3.00 for a regular adult fare. However, students (age 13 to 19) and seniors (age 65 or older) are charged only $2.00. Children 12 and younger ride for free.

Write a program that will ask the user for the age of a passenger. It will then figure out how much to charge that person based on their age.

What we need to learn

  • Learn about writing code with 3 or more pathways for decisions

Basic steps program must perform

  • Create a flowchart of the program

  • Implement the flowchart

Flowchart

Implementation

Now, we implement the program using the same methodology as we did before. We start by putting in all that we know how to do first in the correct sequence and leave out the part that is new.

#include <stdio.h>
int main(void){
    double price;
    int age;
    printf("Please enter the age of the rider: ");
    scanf("%d",&age);

    //figure out price here and store it into price variable

    printf("The price for the rider of age %d is $%.2lf.\n",age, price);
    return 0;

The above program implements everything except for the decision. We just need to figure out what goes inside the comment and we will be done.

the if/else if/else statement

To allow for more than 2 selections, you can extend the if statement with an else if.

if (age <= 12){
    price = 0;
}
else if (age > 19 && age < 65){
    price = 3;
}
else{
    price = 2;
}

The above 3 if/elseif/else statements provide 3 exclusive pathways through the code. One of the 3 paths will always be taken depending on age.

In general, you can have more than one else if, allowing for even more pathways through a decision. General syntax is:

if (age <= 12){
    price = 0;
}
else if (age > 19 && age < 65){
    price = 3;
}
else{
    price = 2;
}

Note that all conditions are processed one after the other. As soon as one is found to be true, all others are skipped.

Thus, our final program looks like this:

#include <stdio.h>
int main(void){
    double price;
    int age;

    printf("Please enter the age of the rider: ");
    scanf("%d",&age);

    if (age <= 12){
        price = 0;
    }
    else if (age > 19 && age < 65){
        price = 3;
    }
    else{
        price = 2;
    }    
    printf("The price for the rider of age %d is $%.2lf.\n",age, price);
    return 0;
}

Last updated