C++ Program To Choose Car By Given Conditions
Automating the car selection process by matching specific criteria can significantly simplify decision-making. Manually sifting through countless models to find one that fits your budget, fuel preference, and capacity needs is time-consuming. In this article, you will learn how to develop a C++ program that recommends a car based on various user-defined conditions.
Problem Statement
The challenge lies in efficiently filtering through a wide range of car options based on a user's specific requirements. These requirements can include budget constraints, preferred fuel type, desired seating capacity, and even additional features. Without an automated system, individuals often spend excessive time comparing models, leading to potential oversight of suitable choices or decision fatigue. The goal is to create a C++ program that takes these conditions as input and provides a relevant car recommendation.
Example
Consider a scenario where a user needs a car and provides their preferences. Here's how a program might interact and provide a recommendation:
Please enter your budget (e.g., 25000): 30000
Enter desired fuel type (petrol, diesel, electric): petrol
Enter minimum seating capacity (e.g., 4, 5, 7): 5
Based on your preferences:
Budget: $30000
Fuel Type: Petrol
Seating Capacity: 5
Recommended Car: A mid-range family sedan like the "Comfort Cruiser" or "EcoDrive 5000".
These offer a good balance of features and efficiency for a family.
Background & Knowledge Prerequisites
To understand and implement the solutions in this article, you should have a basic grasp of:
- C++ Variables and Data Types:
intfor numbers,std::stringfor text. - Input/Output Operations: Using
std::cinto get user input andstd::coutto display information. - Conditional Statements:
if,else if, andelsefor decision-making logic. - Switch Statements: An alternative for handling multiple specific cases.
- Basic Operators: Comparison operators (e.g.,
<,>,<=,>=,==) and logical operators (e.g.,&&for AND,||for OR).
Use Cases or Case Studies
Car selection programs based on conditions are useful in several real-world scenarios:
- Personal Car Shopping Assistant: Individuals can input their specific needs (budget, fuel, size) and quickly get personalized recommendations.
- Automotive Dealership Tools: Sales representatives can use such programs to filter their inventory and present suitable options to customers more efficiently.
- Fleet Management: Companies can use criteria like cargo capacity, fuel efficiency, and maintenance costs to select vehicles for their business operations.
- Online Car Portals: Websites can implement this logic to power their advanced search filters, allowing users to narrow down listings.
- Driving School Vehicle Selection: Choosing appropriate training vehicles based on safety ratings, ease of handling, and cost-effectiveness.
Solution Approaches
We will explore two distinct approaches to building our C++ car selection program, focusing on different ways to handle conditional logic.
Approach 1: Nested if-else Statements for Comprehensive Filtering
This approach uses a series of nested if-else if-else statements to check multiple conditions sequentially. It's straightforward and excellent for beginners learning conditional logic.
One-line Summary: Gathers user input for budget, fuel, and seating, then uses nested if-else blocks to recommend a car.
Code Example:
// Car Recommendation using Nested If-Else
#include <iostream>
#include <string>
#include <limits> // Required for numeric_limits
int main() {
// Step 1: Declare variables to store user preferences
int budget;
std::string fuelType;
int seatingCapacity;
std::cout << "Welcome to the Car Recommendation System!\\n";
// Step 2: Get budget input from the user
std::cout << "Please enter your maximum budget (in USD, e.g., 25000): ";
while (!(std::cin >> budget) || budget <= 0) {
std::cout << "Invalid budget. Please enter a positive number: ";
std::cin.clear(); // Clear error flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'); // Discard invalid input
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'); // Consume the rest of the line
// Step 3: Get fuel type input from the user
std::cout << "Enter desired fuel type (petrol, diesel, electric): ";
std::getline(std::cin, fuelType);
// Step 4: Get seating capacity input from the user
std::cout << "Enter minimum seating capacity (e.g., 4, 5, 7): ";
while (!(std::cin >> seatingCapacity) || seatingCapacity <= 0) {
std::cout << "Invalid seating capacity. Please enter a positive number: ";
std::cin.clear(); // Clear error flag
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'); // Discard invalid input
}
std::cout << "\\n"; // Add a newline for better readability
// Step 5: Display user preferences
std::cout << "Based on your preferences:\\n";
std::cout << "Budget: $" << budget << "\\n";
std::cout << "Fuel Type: " << fuelType << "\\n";
std::cout << "Seating Capacity: " << seatingCapacity << "\\n\\n";
// Step 6: Apply conditional logic to recommend a car
std::string recommendedCar = "No specific recommendation found for your criteria.";
if (budget < 20000) {
if (fuelType == "petrol" && seatingCapacity >= 4) {
recommendedCar = "A compact hatchback or entry-level sedan (e.g., 'City Commuter').";
} else if (fuelType == "electric" && seatingCapacity >= 2) {
recommendedCar = "A small electric city car (e.g., 'Eco Pod').";
}
} else if (budget >= 20000 && budget <= 40000) {
if (fuelType == "petrol" && seatingCapacity >= 5) {
recommendedCar = "A mid-range family sedan or compact SUV (e.g., 'Comfort Cruiser').";
} else if (fuelType == "diesel" && seatingCapacity >= 5) {
recommendedCar = "A fuel-efficient diesel SUV for longer trips (e.g., 'Mileage Master').";
} else if (fuelType == "electric" && seatingCapacity >= 4) {
recommendedCar = "A modern electric sedan or crossover (e.g., 'VoltStream 300').";
}
} else { // budget > 40000
if (fuelType == "petrol" && seatingCapacity >= 5) {
recommendedCar = "A premium sedan or a large SUV (e.g., 'Luxury Drive XL').";
} else if (fuelType == "electric" && seatingCapacity >= 5) {
recommendedCar = "A high-performance luxury electric vehicle (e.g., 'ElectroStar Grand').";
}
}
std::cout << "Recommended Car: " << recommendedCar << "\\n";
return 0;
}
Sample Output:
Welcome to the Car Recommendation System!
Please enter your maximum budget (in USD, e.g., 25000): 35000
Enter desired fuel type (petrol, diesel, electric): electric
Enter minimum seating capacity (e.g., 4, 5, 7): 4
Based on your preferences:
Budget: $35000
Fuel Type: electric
Seating Capacity: 4
Recommended Car: A modern electric sedan or crossover (e.g., 'VoltStream 300').
Stepwise Explanation:
- Variable Declaration:
budget(int),fuelType(string), andseatingCapacity(int) are declared to store user inputs. - User Input: The program prompts the user to enter their budget, preferred fuel type, and minimum seating capacity. Input validation is included to handle non-numeric or invalid entries for budget and seating.
- Display Preferences: The entered preferences are echoed back to the user for confirmation.
- Conditional Logic (Budget): The outer
if-else if-elsestructure categorizes cars based on three budget ranges:< $20,000,$20,000 - $40,000, and> $40,000. - Nested Conditional Logic (Fuel & Seating): Inside each budget block, further
if-else if-elsestatements check thefuelTypeandseatingCapacityto provide a more specific recommendation. This nesting allows for fine-grained control over the recommendation logic. - Recommendation Output: Finally, the program prints the car recommendation that matches the specified criteria. If no specific match is found, a default message is displayed.
Approach 2: Combining switch with if-else for Categorical Choices
This approach demonstrates how to use a switch statement for one categorical condition (like fuel type) and if-else for others (like budget and seating capacity). This can make the code cleaner when one variable has many distinct, known values.
One-line Summary: Uses a switch statement for fuel type and if-else for budget and seating to recommend a car, offering a structured alternative to nested if-else.
Code Example:
// Car Recommendation using Switch and If-Else
#include <iostream>
#include <string>
#include <limits> // Required for numeric_limits
#include <algorithm> // Required for std::transform
int main() {
// Step 1: Declare variables
int budget;
std::string fuelType;
int seatingCapacity;
std::cout << "Welcome to the Advanced Car Recommendation System!\\n";
// Step 2: Get user inputs with validation (similar to Approach 1)
std::cout << "Please enter your maximum budget (in USD, e.g., 25000): ";
while (!(std::cin >> budget) || budget <= 0) {
std::cout << "Invalid budget. Please enter a positive number: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');
std::cout << "Enter desired fuel type (petrol, diesel, electric): ";
std::getline(std::cin, fuelType);
// Convert fuelType to lowercase for consistent comparison
std::transform(fuelType.begin(), fuelType.end(), fuelType.begin(), ::tolower);
std::cout << "Enter minimum seating capacity (e.g., 4, 5, 7): ";
while (!(std::cin >> seatingCapacity) || seatingCapacity <= 0) {
std::cout << "Invalid seating capacity. Please enter a positive number: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');
}
std::cout << "\\n";
// Step 3: Display user preferences
std::cout << "Based on your preferences:\\n";
std::cout << "Budget: $" << budget << "\\n";
std::cout << "Fuel Type: " << fuelType << "\\n";
std::cout << "Seating Capacity: " << seatingCapacity << "\\n\\n";
// Step 4: Apply conditional logic using switch for fuel type and if-else for other conditions
std::string recommendedCar = "No specific recommendation found for your criteria.";
if (budget <= 0 || seatingCapacity <= 0) {
recommendedCar = "Please provide valid positive numbers for budget and seating capacity.";
} else {
switch (fuelType[0]) { // Use the first character for switch for simplicity
case 'p': // petrol
if (budget < 20000 && seatingCapacity >= 4) {
recommendedCar = "A compact petrol hatchback (e.g., 'City Sprint').";
} else if (budget >= 20000 && budget <= 40000 && seatingCapacity >= 5) {
recommendedCar = "A versatile petrol family sedan or SUV (e.g., 'Family Explorer').";
} else if (budget > 40000 && seatingCapacity >= 5) {
recommendedCar = "A powerful petrol luxury car or performance SUV (e.g., 'Veloce Grand').";
}
break;
case 'd': // diesel
if (budget >= 20000 && budget <= 50000 && seatingCapacity >= 5) {
recommendedCar = "A fuel-efficient diesel SUV or sedan for long drives (e.g., 'EcoRoute').";
} else if (budget > 50000 && seatingCapacity >= 6) {
recommendedCar = "A high-torque diesel luxury SUV or minivan (e.g., 'MegaTourer').";
}
break;
case 'e': // electric
if (budget < 30000 && seatingCapacity >= 2) {
recommendedCar = "A compact electric city car with good range (e.g., 'Spark EV').";
} else if (budget >= 30000 && budget <= 60000 && seatingCapacity >= 4) {
recommendedCar = "A mid-range electric sedan or crossover (e.g., 'PowerGlide 400').";
} else if (budget > 60000 && seatingCapacity >= 5) {
recommendedCar = "A premium long-range electric SUV or sedan (e.g., 'Electra Grandeur').";
}
break;
default:
recommendedCar = "Unsupported fuel type. Please choose petrol, diesel, or electric.";
break;
}
}
std::cout << "Recommended Car: " << recommendedCar << "\\n";
return 0;
}
Sample Output:
Welcome to the Advanced Car Recommendation System!
Please enter your maximum budget (in USD, e.g., 25000): 45000
Enter desired fuel type (petrol, diesel, electric): diesel
Enter minimum seating capacity (e.g., 4, 5, 7): 5
Based on your preferences:
Budget: $45000
Fuel Type: diesel
Seating Capacity: 5
Recommended Car: A fuel-efficient diesel SUV or sedan for long drives (e.g., 'EcoRoute').
Stepwise Explanation:
- Variable Declaration and Input: Similar to Approach 1, variables are declared and user input is taken for budget, fuel type, and seating capacity. An important addition is
std::transformto convert thefuelTypeinput to lowercase, ensuring robust comparison in theswitchstatement regardless of user casing. - Display Preferences: User inputs are displayed.
switchStatement for Fuel Type: Theswitchstatement evaluates the first character of thefuelTypestring (fuelType[0]). This allows branching based on 'p' (petrol), 'd' (diesel), or 'e' (electric).- Nested
if-elsefor Budget & Seating: Inside eachcaseof theswitch,if-else if-elsestatements are used to further refine the recommendation based onbudgetandseatingCapacity. defaultCase: Adefaultcase in theswitchhandles any unrecognized fuel types, providing a graceful error message.- Recommendation Output: The final recommendation is printed.
Conclusion
Developing a C++ program to choose a car by given conditions provides a practical demonstration of conditional logic. Both nested if-else statements and a combination of switch with if-else offer effective ways to implement complex decision-making processes. These approaches enable the creation of applications that can filter and recommend items based on multiple user-defined criteria, a valuable skill in various programming contexts.
Summary
- Problem: Manual car selection based on multiple criteria is time-consuming and inefficient.
- Solution: A C++ program uses user input (budget, fuel type, seating) to recommend cars.
- Approach 1 (
if-else if-else): Utilizes nested conditional statements for detailed, sequential filtering of options. - Approach 2 (
switchwithif-else): Combinesswitchfor categorical choices (like fuel type) withif-elsefor numerical ranges, offering structural clarity for certain scenarios. - Key Learning: Mastering conditional logic (
if-else,switch) is crucial for creating programs that respond dynamically to user input and complex rules. - Practicality: These methods are applicable not only to car selection but to any scenario requiring filtering or recommendations based on diverse conditions.