Elective Programming In C

Programming In CUnit 1012 min read

Structures, Unions, Enums: Organizing Data in C

Unit 10 of Programming In C covers structures (grouping related data), unions (memory-efficient alternatives), and enumerations (named integer constants), with real-world applications, syntax, and problem-solving examples.

TAKEAWAYS:

  • Structures group heterogeneous data (e.g., student with roll, name, marks) under one name, enabling logical organization.
  • Unions share memory for multiple variables (e.g., storing either an int or float in the same space), saving memory but risking data corruption.
  • Enumerations assign readable names to integers (e.g., enum {MON, TUE, WED}), improving code clarity.
  • Pointers to structures enable dynamic memory allocation and linked data (e.g., linked lists of records).
  • Nested structures allow hierarchical data (e.g., address inside student).
  • Typedef simplifies complex type declarations (e.g., typedef struct Student student;).

Definition and Syntax

A structure (struct) is a user-defined data type that groups variables of different types under a single name. It is ideal for representing real-world entities like student, employee, or book.

struct Student {
    int roll;
    char name[50];
    float marks;
    char address[100];
};
  • Members: roll (int), name (string), marks (float), address (string).
  • Declaration: struct Student s1; or typedef struct Student student; (simplifies syntax).

Accessing Structure Members

Use the dot (.) operator for direct access or the arrow (->) operator for pointers to structures.

struct Student s1 = {101, "Ramesh", 85.5, "Chitwan"};
printf("Roll: %d, Name: %s", s1.roll, s1.name);

Example: Student Records

Problem: Store n students and display records where address is "Chitwan." Solution:

#include <stdio.h>
#include <string.h>

typedef struct {
    int roll;
    char name[50];
    float marks;
    char address[100];
} Student;

int main() {
    int n, i;
    printf("Enter number of students: ");
    scanf("%d", &n);
    Student students[n];

    for (i = 0; i < n; i++) {
        printf("\nEnter details for student %d:\n", i+1);
        scanf("%d %s %f %s", &students[i].roll, students[i].name, &students[i].marks, students[i].address);
    }

    printf("\nStudents from Chitwan:\n");
    for (i = 0; i < n; i++) {
        if (strcmp(students[i].address, "Chitwan") == 0) {
            printf("Roll: %d, Name: %s, Marks: %.2f\n", students[i].roll, students[i].name, students[i].marks);
        }
    }
    return 0;
}

Trace:

Step Input (n=2) Action Output
1 2 Read n Prompt for student details
2 101 Ramesh 85.5 Chitwan Store in students[0]
3 102 Sita 90.0 Kathmandu Store in students[1]
4 - Compare address with "Chitwan" Roll: 101, Name: Ramesh...

Nested Structures

Use structures inside other structures for hierarchical data (e.g., address inside student).

struct Address {
    char city[50];
    char state[50];
};

struct Student {
    int roll;
    char name[50];
    struct Address addr; // Nested structure
};

Pointers to Structures

Pointers allow dynamic memory allocation and efficient data manipulation.

struct Student *ptr = &s1;
printf("Roll: %d", (*ptr).roll); // or ptr->roll

2. Unions: Memory Efficiency at a Cost

Definition and Syntax

A union shares memory for all members, so only one member can hold a value at a time. Useful for storing heterogeneous data in limited space (e.g., int or float in the same variable).

union Data {
    int i;
    float f;
    char str[20];
};
  • Memory: Only enough to hold the largest member (e.g., char[20] if largest).
  • Access: Same as structures (unionName.member).

Example: Storing Different Data Types

union Data value;
value.i = 10; // Stores 10 in the union's memory
printf("%d", value.i); // Output: 10
value.f = 220.5; // Overwrites the same memory
printf("%f", value.f); // Output: 220.500000

Comparison: Structure vs. Union

Feature Structure Union
Memory Sum of all members Size of the largest member
Data Access All members can be used simultaneously Only one member can hold data at a time
Use Case Logical grouping (e.g., student) Memory optimization (e.g., int or float)
Example struct { int a; float b; }; union { int a; float b; };

When to Use Unions

  • Network packets: Storing different header types in the same space.
  • Embedded systems: Saving memory for sensor data (e.g., int temperature or float humidity).
  • Database records: Storing optional fields (e.g., ID or name).

3. Enumerations: Named Integer Constants

Definition and Syntax

An enumeration (enum) assigns readable names to integer constants, improving code clarity.

enum Day {MON, TUE, WED, THU, FRI, SAT, SUN};
  • Default values: MON=0, TUE=1, ..., SUN=6.
  • Custom values: enum {MON=1, TUE=2, ...}.

Example: Days of the Week

enum Day {MON, TUE, WED, THU, FRI, SAT, SUN};
enum Day today = WED;
printf("Day %d", today); // Output: Day 2

Applications

  • State machines: Representing states (e.g., enum {IDLE, RUNNING, PAUSED}).
  • Menu systems: enum {EXIT, SAVE, LOAD} for user choices.
  • Error codes: enum {SUCCESS, FILE_NOT_FOUND, INVALID_INPUT}.

In the Real World

  1. eSewa (Nepal):

    • Structure: Stores user data (userID, name, balance, transactions) in a structured format for billing and service records.
    • Union: Might use a union to store either a credit_card or mobile_money payment method in the same memory space, optimizing storage.
  2. Khalti (Digital Wallet):

    • Enumeration: Uses enum TransactionType {DEPOSIT, WITHDRAWAL, TRANSFER} to categorize transactions clearly in the backend.
    • Structure: Each transaction is stored as a struct {userID, amount, type, timestamp} for auditing.
  3. Pathao (Ride-Hailing):

    • Nested Structures: Represents a ride as:
      struct Ride {
          struct {
              char source[50];
              char destination[50];
          } location;
          float distance;
          float fare;
      };
      
    • Union: Stores either driverID or passengerID in the same memory for ride history.
  4. NTC (Nepal Telecom):

    • Structure: Customer records include accountID, name, phoneNumber, planType, and usageData.
    • Example: Calculating bill for a customer with planType = "POSTPAID" and usage = 5GB:
      struct Plan {
          char type[20];
          float costPerGB;
      };
      struct Customer {
          int accountID;
          char name[50];
          struct Plan plan;
          float usage;
      };
      
      Calculation:
      struct Customer c1 = {1001, "Rohan", {"POSTPAID", 50}, 5.0};
      float bill = c1.plan.costPerGB * c1.usage;
      printf("Bill: Rs. %.2f", bill); // Output: Rs. 250.00
      

4. Practical Applications

a) Student Record System (Exam Question)

Problem: Store n students and display records where address is "Chitwan." Solution (as above) uses a structure to group student data and a loop to filter records.

b) Memory-Efficient Data Storage

Problem: Store either an int (ID) or float (score) for each student. Solution: Use a union to save memory.

union StudentData {
    int id;
    float score;
};

struct Student {
    char name[50];
    union StudentData data;
    char type; // 'I' for ID, 'S' for score
};

int main() {
    struct Student s1 = {"Ramesh", {.id = 101}, 'I'};
    printf("ID: %d\n", s1.data.id); // Output: 101
    s1.data.score = 85.5;
    s1.type = 'S';
    printf("Score: %.2f\n", s1.data.score); // Output: 85.50
}

c) Traffic Light Control System

Problem: Represent traffic light states (RED, YELLOW, GREEN). Solution: Use an enumeration.

enum TrafficLight {RED, YELLOW, GREEN};
enum TrafficLight current = GREEN;
printf("Current light: %d", current); // Output: 2

Visualizations

1. Structure vs. Union Memory Layout

Key Insight:

  • Structure: Allocates 158 bytes (sum of all members).
  • Union: Allocates 20 bytes (size of the largest member, str[20]).

2. Nested Structure for Student and Address

StudentAddress
Nested structure showing Student containing Address (1:1 relationship)

3. Union in Action: Storing ID or Score

Warning: Assigning score overwrites id in the same memory space!


4. Enumeration for Days of the Week


5. Algorithm: Filtering Students by Address

Code:

for (i = 0; i < n; i++) {
    if (strcmp(students[i].address, "Chitwan") == 0) {
        printf("Roll: %d, Name: %s\n", students[i].roll, students[i].name);
    }
}

Trace:

Step i address Condition (strcmp) Action
1 0 "Chitwan" 0 (match) Print student[0]
2 1 "Kathmandu" Non-zero (no match) Skip

Exam Tip

  1. Differentiate Structure vs. Union:

    • Structure: All members exist simultaneously; memory = sum of all members.
    • Union: Only one member holds data; memory = size of the largest member.
    • Example: In exams, if asked to "save memory," use a union; if grouping data logically, use a structure.
  2. Typedef Shortcut:

    • Always use typedef to simplify declarations (e.g., typedef struct Student student;).
    • Marks Tip: Examiners love clean, readable code. Avoid repeating struct Student everywhere.
  3. Nested Structures:

    • Common in exam questions (e.g., address inside student). Draw a class diagram (like above) to visualize.
  4. Enumerations:

    • Use for fixed sets of constants (e.g., days, states, menu options).
    • Common Mistake: Forgetting to assign custom values (e.g., enum {MON=1, TUE=2}). Default starts at 0.
  5. Pointers to Structures:

    • Questions often ask to dynamically allocate structures (e.g., linked lists).
    • Example:
      struct Student *ptr = malloc(sizeof(struct Student));
      ptr->roll = 101; // Arrow operator for pointers
      
  6. Real-World Scenarios:

    • eSewa/Khalti: Use structures for user data and enums for transaction types.
    • Pathao: Nested structures for ride details (location.source, location.destination).
    • NTC: Unions to store either call_duration (float) or data_used (int) in the same space.
  7. Common Pitfalls:

    • Union Data Corruption: Assigning a new member overwrites previous data. Always track which member is active.
    • String Length: In structures, declare strings with a fixed size (e.g., char name[50]), not dynamically.
    • Initialization: Use {} for partial initialization (e.g., struct Student s1 = {101, "Ramesh"}; initializes roll and name).

Final Checklist for Full Marks

Concept What to Include in Answer Marks Weight
Structure Definition Syntax, members, dot/arrow operators 2
Union Definition Memory sharing, risks, use cases 2
Enum Definition Named constants, default/custom values 1
Nested Structures Example with address inside student 2
Pointers to Structures malloc, arrow operator (->) 2
Real-World Application eSewa/Khalti/Pathao example 3
Code Example Correct syntax, input/output trace 4
Comparison Table Structure vs. Union (memory, use case) 2

Pro Tip: For 8-hour questions, spend 2 hours on theory (definitions, comparisons) and 6 hours on coding + tracing. Always draw diagrams for nested structures or memory layouts—they fetch extra marks!

Based on the PU BE Computer (PU) syllabus for Programming In C, unit 10.

Discussion

Loading…