C Online Compiler
Example: Car Selector with Switch and Nested Conditions in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Car Selector with Switch and Nested Conditions #include <stdio.h> #include <string.h> // Required for strcmp int main() { // Step 1: Declare variables for car criteria int price, fuel_efficiency, seating_capacity; char car_type[20]; // Step 2: Get car details from user printf("Enter car type (Sedan, SUV, Hatchback, Sports): "); scanf("%19s", car_type); printf("Enter car price: $"); scanf("%d", &price); printf("Enter car fuel efficiency (MPG): "); scanf("%d", &fuel_efficiency); printf("Enter car seating capacity: "); scanf("%d", &seating_capacity); // Step 3: Apply conditions using a switch statement for car type printf("\nEvaluating car...\n"); // Convert car_type to an integer for switch (simple hash or enum for more types) // For simplicity, we'll manually check and set a "type_code" // In a real application, you might use enums or more robust string handling int type_code = 0; // 1: Sedan, 2: SUV, 3: Hatchback, 4: Sports if (strcmp(car_type, "Sedan") == 0) type_code = 1; else if (strcmp(car_type, "SUV") == 0) type_code = 2; else if (strcmp(car_type, "Hatchback") == 0) type_code = 3; else if (strcmp(car_type, "Sports") == 0) type_code = 4; else type_code = 0; // Unknown type switch (type_code) { case 1: // Sedan if (price <= 30000 && fuel_efficiency >= 30 && seating_capacity >= 4) { printf("This Sedan is a great choice for balanced performance and family use.\n"); } else { printf("This Sedan doesn't quite meet typical criteria for its type.\n"); } break; case 2: // SUV if (price <= 50000 && fuel_efficiency >= 20 && seating_capacity >= 5) { printf("This SUV is suitable for families and versatility.\n"); } else { printf("This SUV doesn't quite meet typical criteria for its type.\n"); } break; case 3: // Hatchback if (price <= 25000 && fuel_efficiency >= 35 && seating_capacity >= 4) { printf("This Hatchback is excellent for city driving and fuel economy.\n"); } else { printf("This Hatchback doesn't quite meet typical criteria for its type.\n"); } break; case 4: // Sports Car if (price >= 40000 && fuel_efficiency >= 15 && seating_capacity >= 2) { printf("This Sports Car is a high-performance, enthusiast's choice.\n"); } else { printf("This Sports Car doesn't quite meet typical criteria for its type.\n"); } break; default: printf("Car type not recognized or no specific recommendations available.\n"); break; } return 0; }
Output
Clear
ADVERTISEMENTS