Update Q4.c
This commit is contained in:
11
Q4.c
11
Q4.c
@@ -1,6 +1,6 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <string.h>
|
|
||||||
|
|
||||||
|
// union for book
|
||||||
typedef union Book {
|
typedef union Book {
|
||||||
char title[50];
|
char title[50];
|
||||||
char author[50];
|
char author[50];
|
||||||
@@ -8,6 +8,8 @@ typedef union Book {
|
|||||||
double price;
|
double price;
|
||||||
} Book;
|
} Book;
|
||||||
|
|
||||||
|
//Print book details
|
||||||
|
// Note that this is impossible since Book is a union, it cannot have all these details initialized at once
|
||||||
void print_book(Book *book) {
|
void print_book(Book *book) {
|
||||||
printf("Title: %s\n", book->title);
|
printf("Title: %s\n", book->title);
|
||||||
printf("Author: %s\n", book->author);
|
printf("Author: %s\n", book->author);
|
||||||
@@ -15,6 +17,7 @@ void print_book(Book *book) {
|
|||||||
printf("Price: %0.02f\n\n", book->price);
|
printf("Price: %0.02f\n\n", book->price);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Prints all books with price higher than threshold
|
||||||
void print_books_higher_than_threshold(Book arr[], int len, double threshold) {
|
void print_books_higher_than_threshold(Book arr[], int len, double threshold) {
|
||||||
for(int i = 0; i < len; i++) {
|
for(int i = 0; i < len; i++) {
|
||||||
if(arr[i].price > threshold) {
|
if(arr[i].price > threshold) {
|
||||||
@@ -24,6 +27,7 @@ void print_books_higher_than_threshold(Book arr[], int len, double threshold) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
|
// Books to test function
|
||||||
Book b1;
|
Book b1;
|
||||||
b1.price = 2.99;
|
b1.price = 2.99;
|
||||||
Book b2;
|
Book b2;
|
||||||
@@ -37,9 +41,8 @@ int main() {
|
|||||||
|
|
||||||
/* Ok so this kinda doesnt make sense. The threshold check only works if Book is set with a price. Kinda goes in
|
/* Ok so this kinda doesnt make sense. The threshold check only works if Book is set with a price. Kinda goes in
|
||||||
* line with the fact that union doesnt make sense at all here
|
* line with the fact that union doesnt make sense at all here
|
||||||
* Also, when printing any book, since only 1 value is assigned (as its a UNION) the other fields are gibberish
|
* Also, when printing any book, since only 1 value is assigned (as its a union) the other fields are gibberish
|
||||||
|
* */
|
||||||
|
|
||||||
print_books_higher_than_threshold(arr, sizeof(arr)/sizeof(arr[0]), 10.0);
|
print_books_higher_than_threshold(arr, sizeof(arr)/sizeof(arr[0]), 10.0);
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user