From f1979dc1127d5d0317c91a448d253e6940172c9a Mon Sep 17 00:00:00 2001 From: Madeline Busig Date: Thu, 31 Oct 2024 01:05:33 -0700 Subject: [PATCH] Add problem 9 solution --- include/p9.h | 14 ++++++++++++++ src/main.c | 19 +++++++++++++++++++ src/p9.c | 16 ++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 include/p9.h create mode 100644 src/p9.c diff --git a/include/p9.h b/include/p9.h new file mode 100644 index 0000000..10001a9 --- /dev/null +++ b/include/p9.h @@ -0,0 +1,14 @@ +#ifndef P9_H +#define P9_H + +typedef struct { + int id; + char name[32]; + double price; + int stock; +} Product; + +Product* find_product(Product* products, int num_products, int id); + +#endif + diff --git a/src/main.c b/src/main.c index 7576133..f14bc4c 100644 --- a/src/main.c +++ b/src/main.c @@ -8,6 +8,7 @@ #include "p6.h" #include "p7.h" #include "p8.h" +#include "p9.h" void print_int_arr(int* arr, int size) { for (int i = 0; i < size; ++i) { @@ -95,6 +96,24 @@ int main(void) { printf("Average GPA: %.2lf\n", average_gpa); + // Problem 9 + printf("Problem 9:\n"); + + Product products[4] = { + { 4011, "Banana", 10.0, 1000 }, + { 412, "Apple", 2.5, 240 }, + { 728, "Pear", 4.8, 180 }, + { 119, "Orange", 1.6, 438 }, + }; + + Product* found = find_product(products, 4, 728); + + if (found != NULL) { + printf("Found product \"%s\" with id %d\n", found->name, found->id); + } else { + printf("Did not find any matching products!\n"); + } + return 0; } diff --git a/src/p9.c b/src/p9.c new file mode 100644 index 0000000..7ef3bed --- /dev/null +++ b/src/p9.c @@ -0,0 +1,16 @@ +#include "p9.h" + +#include + +Product* find_product(Product* products, int num_products, int id) { + Product* found = NULL; + + for (int i = 0; i < num_products; ++i) { + if (products[i].id == id) { + found = &products[i]; + } + } + + return found; +} +