From 94d003bf68584d9d710e255f1024dbae19b8cbad Mon Sep 17 00:00:00 2001 From: Alex Date: Tue, 22 Oct 2024 21:53:34 -0700 Subject: [PATCH] Update Q3.C --- Q3.C | 68 ++++++++++++++++++++++++++++++++++-------------------------- 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/Q3.C b/Q3.C index c40f2a4..5882959 100644 --- a/Q3.C +++ b/Q3.C @@ -1,51 +1,61 @@ #include +// Struct for Car typedef struct Car { - char model[50]; - int year; - double price; - - + char model[50]; + int year; + double price; } Car; +// Print details of passed car pointer void display_details(Car *car) { - printf("Model: %s\n", car->model); - printf("Year: %d\n", car->year); - printf("Price: %0.02f\n", car->price); + printf("Model: %s\n", car->model); + printf("Year: %d\n", car->year); + printf("Price: $%0.02f\n", car->price); } // Returns a pointer to the car with the lowest price Car *find_lowest_price(Car arr[], int len) { - int lowest_price = arr[0].price; - Car *lowest = &arr[0]; - for(int i = 1; i < len; i++) { - if(arr[i].price < lowest_price) { - lowest_price = arr[i].price; - lowest = &arr[i]; - } - } - return lowest; + int lowest_price = arr[0].price; + Car *lowest = &arr[0]; + for(int i = 1; i < len; i++) { + if(arr[i].price < lowest_price) { + lowest_price = arr[i].price; + lowest = &arr[i]; + } + } + return lowest; } +// Returns double of average price of the cars double find_average_price(Car arr[], int len) { - double average = 0; - for(int i = 0; i < len; i++) { - average += arr[i].price; - } - return average / len; + double average = 0; + for(int i = 0; i < len; i++) { + average += arr[i].price; + } + return average / len; } int main() { - Car c1 = {"Honda Pilot", 2016, 20000.50}; - Car c2 = {"Chevy Tahoe", 2002, 7500.25}; - Car c3 = {"Lamborghini Aventador", 2015, 450000}; + // Cars to test function and struct + Car c1 = {"Honda Pilot", 2016, 20000.50}; + Car c2 = {"Chevy Tahoe", 2002, 7500.25}; + Car c3 = {"Lamborghini Aventador", 2015, 450000}; - Car arr[] = {c1, c2, c3}; + Car arr[] = {c1, c2, c3}; - display_details(find_lowest_price(arr, 3)); + // Display all car details + for(int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { + display_details(&arr[i]); + } - printf("Average price: %0.02f\n", find_average_price(arr, 3)); + //Print car with lowest price + printf("\nCar with the lowest price: "); + display_details(find_lowest_price(arr, 3)); - return 0; + //Print average price of the cars + printf("\nAverage price: $%0.02f\n", find_average_price(arr, 3)); + + return 0; }