Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

C Programming Practice Implementations for Struct, Enum and Collection Operations

Tech 1
#include <stdio.h>
#define MAX_BOOK_ENTRIES 10

typedef struct {
    char isbn[20];
    char book_title[80];
    char author_name[80];
    double unit_price;
    int units_sold;
} CatalogItem;

void print_catalog(CatalogItem entries[], int count);
void sort_by_sales_volume(CatalogItem entries[], int count);
double compute_total_revenue(CatalogItem entries[], int count);

int main() {
    CatalogItem inventory[MAX_BOOK_ENTRIES] = {
        {"978-7-5327-6082-4", "The Death of the Goalkeeper", "Ronald Reng", 42, 51},
        {"978-7-308-17047-5", "Land of Freedom and Love: Notes from Israel", "Yun Yetui", 49, 30},
        {"978-7-5404-9344-8", "Londoners", "Craig Taylor", 68, 27},
        {"978-7-5447-5246-6", "The Lifecycle of Software Objects", "Ted Chiang", 35, 90},
        {"978-7-5722-5475-8", "A Brief History of Microchips", "Wang Bo", 74.9, 49},
        {"978-7-5133-5750-0", "Console Wars", "Blake J. Harris", 128, 42},
        {"978-7-2011-4617-1", "The Cafe at the Edge of the World", "John Strelecky", 22.5, 44},
        {"978-7-5133-5109-6", "Hello Aliens", "Future Publishing UK", 118, 42},
        {"978-7-1155-0509-5", "The Beginning of Infinity: Explanations That Transform the World", "David Deutsch", 37.5, 55},
        {"978-7-229-14156-1", "The Fountainhead", "Ayn Rand", 84, 59}
    };

    printf("Book sales ranking (sorted by units sold descending):\n");
    sort_by_sales_volume(inventory, MAX_BOOK_ENTRIES);
    print_catalog(inventory, MAX_BOOK_ENTRIES);

    printf("\nTotal book sales revenue: %.2f\n", compute_total_revenue(inventory, MAX_BOOK_ENTRIES));
    return 0;
}

void sort_by_sales_volume(CatalogItem entries[], int count) {
    for (int outer = 0; outer < count; outer++) {
        for (int inner = 0; inner < count - outer - 1; inner++) {
            if (entries[inner].units_sold < entries[inner + 1].units_sold) {
                CatalogItem temp = entries[inner];
                entries[inner] = entries[inner + 1];
                entries[inner + 1] = temp;
            }
        }
    }
}

void print_catalog(CatalogItem entries[], int count) {
    for (int idx = 0; idx < count; idx++) {
        if ((int)entries[idx].unit_price != entries[idx].unit_price) {
            printf("%-20s%-30s%-25s%-20.1lf%-20d\n",
                entries[idx].isbn, entries[idx].book_title, entries[idx].author_name,
                entries[idx].unit_price, entries[idx].units_sold);
        } else {
            printf("%-20s%-30s%-25s%-20.lf%-20d\n",
                entries[idx].isbn, entries[idx].book_title, entries[idx].author_name,
                entries[idx].unit_price, entries[idx].units_sold);
        }
    }
}

double compute_total_revenue(CatalogItem entries[], int count) {
    double total = 0.0;
    for (int idx = 0; idx < count; idx++) {
        total += entries[idx].units_sold * entries[idx].unit_price;
    }
    return total;
}
#include <stdio.h>

typedef struct {
    int year;
    int month;
    int day;
} CalendarDate;

void read_date(CalendarDate *date_ptr);
int get_day_of_year(CalendarDate date);
int compare_calendar_dates(CalendarDate date_a, CalendarDate date_b);

void test_day_calculation() {
    CalendarDate input_date;
    for (int run = 0; run < 3; run++) {
        printf("Enter date in YYYY-MM-DD format:\n");
        read_date(&input_date);
        printf("%d-%02d-%02d is the %dth day of the year\n\n",
            input_date.year, input_date.month, input_date.day, get_day_of_year(input_date));
    }
}

void test_age_comparison() {
    CalendarDate alice_dob, bob_dob;
    for (int run = 0; run < 3; run++) {
        printf("Enter Alice and Bob's birth dates in YYYY-MM-DD format:\n");
        read_date(&alice_dob);
        read_date(&bob_dob);
        int cmp_res = compare_calendar_dates(alice_dob, bob_dob);
        if (cmp_res == 0) {
            printf("Alice and Bob are of the same age\n\n");
        } else if (cmp_res == -1) {
            printf("Alice is older than Bob\n\n");
        } else {
            printf("Alice is younger than Bob\n\n");
        }
    }
}

int main() {
    printf("Test 1: Calculate day ordinal of a given date\n");
    test_day_calculation();

    printf("\nTest 2: Compare birth dates to determine age relation\n");
    test_age_comparison();
    return 0;
}

void read_date(CalendarDate *date_ptr) {
    int y, m, d;
    scanf("%d-%d-%d", &y, &m, &d);
    date_ptr->year = y;
    date_ptr->month = m;
    date_ptr->day = d;
}

int get_day_of_year(CalendarDate date) {
    int month_day_counts[] = {31,28,31,30,31,30,31,31,30,31,30,31};
    int ordinal = date.day;
    if ((date.year % 4 == 0 && date.year % 100 != 0) || (date.year % 400 == 0)) {
        month_day_counts[1] = 29;
    }
    for (int i = 0; i < date.month - 1; i++) {
        ordinal += month_day_counts[i];
    }
    return ordinal;
}

int compare_calendar_dates(CalendarDate date_a, CalendarDate date_b) {
    if (date_a.year != date_b.year) {
        return date_a.year > date_b.year ? 1 : -1;
    }
    if (date_a.month != date_b.month) {
        return date_a.month > date_b.month ? 1 : -1;
    }
    if (date_a.day != date_b.day) {
        return date_a.day > date_b.day ? 1 : -1;
    }
    return 0;
}
#include <stdio.h>
#include <string.h>

enum UserRole { ADMIN, STUDENT, TEACHER };

typedef struct {
    char username[20];
    char password[20];
    enum UserRole role;
} UserAccount;

void print_accounts(UserAccount accounts[], int count);

int main() {
    UserAccount account_list[] = {
        {"A1001", "123456", STUDENT},
        {"A1002", "123abcdef", STUDENT},
        {"A1009", "xyz12121", STUDENT},
        {"X1009", "9213071x", ADMIN},
        {"C11553", "129dfg32k", TEACHER},
        {"X3005", "921kfmg917", STUDENT}
    };
    int total_accounts = sizeof(account_list) / sizeof(UserAccount);
    print_accounts(account_list, total_accounts);
    return 0;
}

void print_accounts(UserAccount accounts[], int count) {
    for (int idx = 0; idx < count; idx++) {
        int pwd_len = strlen(accounts[idx].password);
        printf("%-10s", accounts[idx].username);
        for (int pos = 0; pos < pwd_len; pos++) {
            putchar('*');
        }
        for (int pos = pwd_len; pos < 20; pos++) {
            putchar(' ');
        }
        switch(accounts[idx].role) {
            case STUDENT: printf("student\n"); break;
            case ADMIN: printf("admin\n"); break;
            case TEACHER: printf("teacher\n"); break;
            default: printf("unknown\n");
        }
    }
}
#include <stdio.h>
#include <string.h>

typedef struct {
    char full_name[20];
    char phone_number[12];
    int is_urgent;
} AddressEntry;

void mark_urgent_contact(AddressEntry entries[], int count, char target_name[]);
void print_address_entries(AddressEntry entries[], int count);
void sort_address_book(AddressEntry entries[], int count);

#define MAX_CONTACTS 10
int main() {
    AddressEntry contact_list[MAX_CONTACTS] = {
        {"Liu Yi", "15510846604", 0},
        {"Chen Er", "18038747351", 0},
        {"Zhang San", "18853253914", 0},
        {"Li Si", "13230584477", 0},
        {"Wang Wu", "15547571923", 0},
        {"Zhao Liu", "18856659351", 0},
        {"Zhou Qi", "17705843215", 0},
        {"Sun Ba", "15552933732", 0},
        {"Wu Jiu", "18077702405", 0},
        {"Zheng Shi", "18820725036", 0}
    };
    int urgent_count;
    char input_name[20];

    printf("Original address book entries:\n");
    print_address_entries(contact_list, MAX_CONTACTS);

    printf("\nEnter number of urgent contacts to set: ");
    scanf("%d", &urgent_count);

    printf("Enter %d contact names to mark as urgent:\n", urgent_count);
    for (int i = 0; i < urgent_count; i++) {
        scanf("%s", input_name);
        mark_urgent_contact(contact_list, MAX_CONTACTS, input_name);
    }

    printf("\nSorted address book (urgent contacts first, sorted by name ascending):\n");
    sort_address_book(contact_list, MAX_CONTACTS);
    print_address_entries(contact_list, MAX_CONTACTS);
    return 0;
}

void mark_urgent_contact(AddressEntry entries[], int count, char target_name[]) {
    for (int i = 0; i < count; i++) {
        if (strcmp(entries[i].full_name, target_name) == 0) {
            entries[i].is_urgent = 1;
            return;
        }
    }
}

void sort_address_book(AddressEntry entries[], int count) {
    for (int outer = 0; outer < count; outer++) {
        for (int inner = 0; inner < count - outer - 1; inner++) {
            int swap_needed = 0;
            if (entries[inner].is_urgent < entries[inner + 1].is_urgent) {
                swap_needed = 1;
            } else if (entries[inner].is_urgent == entries[inner + 1].is_urgent) {
                if (strcmp(entries[inner].full_name, entries[inner + 1].full_name) > 0) {
                    swap_needed = 1;
                }
            }
            if (swap_needed) {
                AddressEntry temp = entries[inner];
                entries[inner] = entries[inner + 1];
                entries[inner + 1] = temp;
            }
        }
    }
}

void print_address_entries(AddressEntry entries[], int count) {
    for (int i = 0; i < count; i++) {
        printf("%-12s%-15s", entries[i].full_name, entries[i].phone_number);
        if (entries[i].is_urgent) {
            printf("%4s", "*");
        }
        printf("\n");
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.