Add problem 9 solution

This commit is contained in:
Myles Busig 2024-10-31 01:05:33 -07:00
parent 56ac8c91f8
commit 3610120c57
3 changed files with 49 additions and 0 deletions

14
include/p9.h Normal file
View File

@ -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

View File

@ -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;
}

16
src/p9.c Normal file
View File

@ -0,0 +1,16 @@
#include "p9.h"
#include <stddef.h>
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;
}