Deterimining Transit Fare
Consider the problem of determining the cost of a single fare paid in cash on the TTC. https://www.ttc.ca/Fares-and-passes
In this problem, the age of the rider determines the fare. Currently the fares are as follows:
- children: 12 and under - free
- youth: 13 to 19 inclusive - $2.40
- adults: - $3.35
- seniors: 65 or older - $2.30
Here is a sample run:
Please enter the age of the rider: 15
Rider of age 15 must pay a fare of $2.40
This is what our program will need to do:
- Ask the user to enter their age and read that value in
- Determine the cost of the fare based on age
- Print the result
The difference between this problem and the muffin problem is that there are 4 different fares based on age. Thus, we essentially need a way to talk about taking 4 different paths.
Mutually exclusive conditions
This problem involves a set of mutually exclusive conditions. That is, a person can only be one age and none of the fare categories have overlapping ages. Thus, the decision of which fare can only be one of the 4 options (children, youth, adults, seniors). No one can be more than one of these. This is a set of mutually exclusive conditions.
This flow chart shows how we cascade multiple selections to come to our result.
In practice, what we do is employ the if/else if/.../else construct
if (condition1){
...
}
else if (condition2){
...
}
else if (condition3){
...
}
else if (condition4){
...
}
else{
...
}
The two conditions for 12 and under or 65 and over are fairly easy to construct. The condition for between 13 and 19 however requires a more complicated construction
Consider the following number line
This all numbers 13 or higher is represented by the arrow pointing to the right. All number 19 or lower is represented by the arrow pointing to the left.
We are interested in only those numbers that are are between 13 and 19. Looking at this number line, we see that this is the portion where both conditions (13 or higher) and (19 or lower) are true. Thus we connect these two checks conditions with the and (&&) operator.
Final program:
Putting all this together:
#include <stdio.h>
int getAge();
double calculateFare(int age);
void printResult(int age, double fare);
int main(void){
int age = getAge();
double fare = calculateFare(age);
printResult(age,fare);
}
int getAge(){
int age;
printf("Please enter the age of the rider: ");
scanf("%d", &age);
return age;
}
void printResult(int age, double fare){
printf("Rider of age %d must pay a fare of $%.2lf\n",age, fare);
}
double calculateFare(int age){
double fare;
if(age < 12){
fare = 0;
}
else if (age >= 13 && age <= 19){
fare = 2.40;
}
else if (age > 65){
fare = 2.30;
}
else{
fare = 3.35;
}
return fare;
}