Ticket Price Calculator: Age-Based Conditional Logic in C++
In this C++ exercise, you will create a program that calculates the price of a ticket based on the age of the user. Different age groups are often charged different prices for events, transportation, or attractions. This program helps simulate such a pricing system.
This task enhances your understanding of input handling, conditional logic, and control structures in C++. By the end of the exercise, you'll be comfortable using if-else statements to create dynamic behaviors based on user input.
Core Concepts
Conditional Logic
Using if-else if ladders allows the program to evaluate multiple conditions in sequence until a match is found for the user's age.
Range Validation
Combined logical operators like && (AND) ensure that the age falls strictly within the defined boundaries for each price bracket.
Pro Tip: Order Matters!
When using if-else if, always arrange your conditions logically. Checking ranges from youngest to oldest (or vice versa) prevents logical overlaps and bugs.
Objectives
- 1. Prompt the user to enter their age.
- 2. Determine the price: 0-4 (Free), 5-17 ($5), 18-64 ($10), 65+ ($6).
- 3. Use an
elseblock to handle invalid (negative) age inputs. - 4. Display the final ticket price formatted with a dollar sign.
Example C++ Code
#include <iostream>
using namespace std;
int main() {
int age;
int ticketPrice;
cout << "Enter your age: ";
cin >> age;
// 1. Evaluate age using conditional structures
if (age >= 0 && age <= 4) {
ticketPrice = 0; // Children under 5 are free
} else if (age >= 5 && age <= 17) {
ticketPrice = 5; // Minors pay $5
} else if (age >= 18 && age <= 64) {
ticketPrice = 10; // Adults pay $10
} else if (age >= 65) {
ticketPrice = 6; // Seniors pay $6
} else {
// 2. Handle invalid input
cout << "Invalid age entered." << endl;
return 1;
}
// 3. Output results
cout << "Your ticket price is: $" << ticketPrice << endl;
return 0;
}
Console Output:
Your ticket price is: $6