9 Structures And Unions

C Programming · Unit 9

Structures and Unions

Exam-focused notes for Structures and Unions (C Programming, BIT102): what the TU syllabus asks and how it has actually been tested, with 8 solved past questions from this unit.

Structures and Unions in short

Arrays hold items of one type. Structures and unions group items of different types into one unit, which is how records such as students or employees are stored.

Structures and Unions: notes

Structure definition and initialization

A structure is a user-defined type that groups variables of different types under one name. It is made with the struct keyword.

struct student {
    int roll;
    char name[30];
    float marks;
};

struct student s1 = {1, "Sita", 82.5f};
struct student s2;      /* uninitialized */

The definition only creates a new type. Memory is given when a variable is declared. Members are stored one after another in memory, and the compiler may add padding between them.

Structure members and access

Use the dot operator . to reach a member of a structure variable. Use the arrow operator -> when you have a pointer to the structure.

struct student s1 = {1, "Sita", 82.5f};
struct student *p = &s1;

printf("%s\n", s1.name);     /* dot */
printf("%d\n", p->roll);     /* arrow, same as (*p).roll */
s1.marks = 90;

Strings cannot be assigned with =. Use strcpy(s1.name, "Gita");. Two structures of the same type can be copied with s2 = s1;.

Nested structures

A structure can have another structure as a member. This is a nested structure.

struct date {
    int day, month, year;
};

struct employee {
    int id;
    char name[30];
    struct date joined;
};

struct employee e = {101, "Ram", {15, 6, 2024}};
printf("%d/%d/%d\n", e.joined.day, e.joined.month, e.joined.year);

Use the dot operator once for each level, from outside to inside.

What this unit covers

  • Structure definition and initialization
  • Structure members and access
  • Nested structures
  • Union definition and initialization
  • Differences between structure and union
  • Typedef keyword
  • Storing and displaying structure data
  • Filtering structure records

Storing and displaying structure data

2081 · 5 marks

What is structure? Write a program to read roll, name and marks of 10 students using structure and then display all records. [1+4]

Show solved answer

Structure in C

What is Structure?

A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable inside a structure is called a member or field.

Syntax:

struct structure_name {
    data_type member1;
    data_type member2;
    ...
};

Program: Read and Display Records of 10 Students

#include <stdio.h>

// Define the structure
struct Student {
    int roll;
    char name[50];
    float marks;
};

int main() {
    struct Student s[10];
    int i;

    // Read records of 10 students
    printf("Enter details of 10 students:\n");
    for (i = 0; i < 10; i++) {
        printf("\nStudent %d:\n", i + 1);
        printf("Enter Roll No : ");
        scanf("%d", &s[i].roll);
        printf("Enter Name    : ");
        scanf(" %s", s[i].name);
        printf("Enter Marks   : ");
        scanf("%f", &s[i].marks);
    }

    // Display all records
    printf("\n\n--- Student Records ---\n");
    printf("%-10s %-20s %-10s\n", "Roll No", "Name", "Marks");
    printf("----------------------------------------\n");
    for (i = 0; i < 10; i++) {
        printf("%-10d %-20s %-10.2f\n", s[i].roll, s[i].name, s[i].marks);
    }

    return 0;
}

Sample Output

Enter details of 10 students:

Student 1:
Enter Roll No : 1
Enter Name    : Ram
Enter Marks   : 85.5
...

--- Student Records ---
Roll No    Name                 Marks
----------------------------------------
1          Ram                  85.50
2          Sita                 90.00
...

Key Points

FeatureDescription
Keywordstruct
MembersCan be of different data types
Array of structuresstruct Student s[10] stores 10 students
Member accessUsing dot operator (.)
Open this answer on its own page →

2078 · 5 marks

Write a program to store and display basic information (Roll, name, address, email. and phone) of students of using a structure. [5]

Show solved answer

Program to Store and Display Student Information Using Structure

Concept

A structure in C is a user-defined data type that groups related variables of different data types under a single name.


C Program

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

// Define the structure
struct Student {
    int roll;
    char name[50];
    char address[100];
    char email[50];
    char phone[15];
};

int main() {
    int i, n;

    printf("Enter number of students: ");
    scanf("%d", &n);

    // Declare an array of structures
    struct Student s[n];

    // Input student information
    for (i = 0; i < n; i++) {
        printf("\n--- Enter details for Student %d ---\n", i + 1);

        printf("Roll Number : ");
        scanf("%d", &s[i].roll);

        printf("Name        : ");
        getchar();  // clear input buffer
        fgets(s[i].name, sizeof(s[i].name), stdin);
        s[i].name[strcspn(s[i].name, "\n")] = '\0';  // remove newline

        printf("Address     : ");
        fgets(s[i].address, sizeof(s[i].address), stdin);
        s[i].address[strcspn(s[i].address, "\n")] = '\0';

        printf("Email       : ");
        fgets(s[i].email, sizeof(s[i].email), stdin);
        s[i].email[strcspn(s[i].email, "\n")] = '\0';

        printf("Phone       : ");
        fgets(s[i].phone, sizeof(s[i].phone), stdin);
        s[i].phone[strcspn(s[i].phone, "\n")] = '\0';
    }

    // Display student information
    printf("\n========== Student Information ==========\n");
    for (i = 0; i < n; i++) {
        printf("\nStudent %d:\n", i + 1);
        printf("  Roll Number : %d\n",   s[i].roll);
        printf("  Name        : %s\n",   s[i].name);
        printf("  Address     : %s\n",   s[i].address);
        printf("  Email       : %s\n",   s[i].email);
        printf("  Phone       : %s\n",   s[i].phone);
    }

    return 0;
}

Sample Output

Enter number of students: 2

--- Enter details for Student 1 ---
Roll Number : 101
Name        : Ram Sharma
Address     : Kathmandu
Email       : [email protected]
Phone       : 9841000001

--- Enter details for Student 2 ---
Roll Number : 102
Name        : Sita Thapa
Address     : Pokhara
Email       : [email protected]
Phone       : 9841000002

========== Student Information ==========

Student 1:
  Roll Number : 101
  Name        : Ram Sharma
  Address     : Kathmandu
  Email       : [email protected]
  Phone       : 9841000001

Student 2:
  Roll Number : 102
  Name        : Sita Thapa
  Address     : Pokhara
  Email       : [email protected]
  Phone       : 9841000002

Key Points

FeatureDetail
struct StudentUser-defined structure with 5 members
struct Student s[n]Array of structures to store multiple students
s[i].rollDot operator used to access structure members
fgets()Used to read strings with spaces
Open this answer on its own page →

Union definition and initialization

2081 · 5 marks

Write short notes on: a) Union b) Switch statement [0+2.5+2.5]

A union is a user-defined data type in C that allows storing different data types in the same memory location. All members of a union share the same memory space, and the size of the union is equal to the size of its largest member. Syntax: Example: Key Points: - Only one member can hold a value ...

Open this answer on its own page →

Differences between structure and union

2080 · 10 marks

Differentiate between structure and union? Write a program to read employ id, name, post and salary of employee and display detail of those employee whose post is 'clerk'.[10]

--- Feature Structure Union --------- Keyword struct union Memory Allocation Each member gets its own separate memory All members share the same memory location Total Size Sum of sizes of all members Size of the largest member only Data Storage All members can store values simultaneously Only one...

Open this answer on its own page →

2077 · 10 marks

How structure is different from union? Write a program to store and display basic information (roll, name, address, email, and phone) of students of using a structure.[10]

Show solved answer

Structure vs Union in C

Difference Between Structure and Union

FeatureStructureUnion
Keywordstructunion
Memory AllocationEach member gets its own separate memoryAll members share the same memory location
Total SizeSum of sizes of all membersSize of the largest member only
Data StorageAll members can store values simultaneouslyOnly one member can hold a value at a time
AccessAll members can be accessed at any timeOnly the last written member gives valid data
UsageWhen all data fields are needed togetherWhen only one field is needed at a time (saves memory)

Example of size difference:

struct S { int a; float b; char c; };
// Size = 4 + 4 + 1 = 9 bytes (approx, with padding)

union U { int a; float b; char c; };
// Size = 4 bytes (size of largest member: int or float)

C Program to Store and Display Student Information Using Structure

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

// Define the structure for student information
struct Student {
    int roll;
    char name[50];
    char address[100];
    char email[50];
    char phone[15];
};

int main() {
    int i, n;

    printf("Enter the number of students: ");
    scanf("%d", &n);

    // Declare an array of structures
    struct Student s[n];

    // Input student information
    for (i = 0; i < n; i++) {
        printf("\n--- Enter details for Student %d ---\n", i + 1);

        printf("Roll Number : ");
        scanf("%d", &s[i].roll);

        printf("Name        : ");
        // Clear input buffer before reading string
        getchar();
        fgets(s[i].name, sizeof(s[i].name), stdin);
        s[i].name[strcspn(s[i].name, "\n")] = '\0'; // Remove newline

        printf("Address     : ");
        fgets(s[i].address, sizeof(s[i].address), stdin);
        s[i].address[strcspn(s[i].address, "\n")] = '\0';

        printf("Email       : ");
        fgets(s[i].email, sizeof(s[i].email), stdin);
        s[i].email[strcspn(s[i].email, "\n")] = '\0';

        printf("Phone       : ");
        fgets(s[i].phone, sizeof(s[i].phone), stdin);
        s[i].phone[strcspn(s[i].phone, "\n")] = '\0';
    }

    // Display student information
    printf("\n\n========== Student Information ==========\n");
    for (i = 0; i < n; i++) {
        printf("\nStudent %d:\n", i + 1);
        printf("  Roll Number : %d\n",   s[i].roll);
        printf("  Name        : %s\n",   s[i].name);
        printf("  Address     : %s\n",   s[i].address);
        printf("  Email       : %s\n",   s[i].email);
        printf("  Phone       : %s\n",   s[i].phone);
    }

    return 0;
}

Sample Output

Enter the number of students: 2

--- Enter details for Student 1 ---
Roll Number : 101
Name        : Ram Sharma
Address     : Kathmandu
Email       : [email protected]
Phone       : 9841000001

--- Enter details for Student 2 ---
Roll Number : 102
Name        : Sita Thapa
Address     : Pokhara
Email       : [email protected]
Phone       : 9841000002

========== Student Information ==========

Student 1:
  Roll Number : 101
  Name        : Ram Sharma
  Address     : Kathmandu
  Email       : [email protected]
  Phone       : 9841000001

Student 2:
  Roll Number : 102
  Name        : Sita Thapa
  Address     : Pokhara
  Email       : [email protected]
  Phone       : 9841000002

Key Points to Remember

  • struct Student defines a template/blueprint for student data.
  • The dot operator (.) is used to access structure members.
  • An array of structures (struct Student s[n]) allows storing multiple students.
  • Structure is preferred here because all fields are needed simultaneously.
Open this answer on its own page →

2081.2 · 5 marks

What is union? Differentiate between pointer and array. [5]

--- A union is a user-defined data type in C that allows storing different data types in the same memory location. All members of a union share the same memory space, and the size of the union is equal to the size of its largest member. Syntax: Example: Here, all three members share the same memo...

Open this answer on its own page →

Nested structures

2079 · 10 marks

How nested Structure is defined and initialized? Explain with an example.Write a program, using structure, to input records of 10 students. Members include name, roll number, marks obtained in math, C program and English. Display the records of students who have passed in C Program.[4+6]

(a) Nested Structure - Definition and Initialization A nested structure is a structure that contains another structure as one of its members. In other words, when a struct variable (or definition) is used as a member inside another struct, it is called a nested structure. A nested structure can b...

Open this answer on its own page →

Structure definition and initialization

0 · 10 marks

Define structure. Write syntax for defining and initializing structure?Write a program that stores details of N employees (E_id, E_Name, Salary), and display the details of those employees whose salary is less than 10000.[5+5]

A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable inside a structure is called a member or field. Structures are used to represent a record, such as an employee, student, book, etc. --- Example: --- Example: -...

Open this answer on its own page →