8 Structure And Union

C Programming · Unit 8 · 5 hrs

Structure and Union

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

Structure and Union in short

This chapter introduces the structure and the union as C's two ways of grouping several, possibly different, data items under a single name.

Structure and Union: notes

Introduction

A structure is a collection of logically related data items, called members, grouped together under one name; because its members can be of different types, a structure is described as a heterogeneous, user-defined data type. It is defined with the keyword struct followed by a tag name:

struct student {
    char name[15];
    int roll;
    float fee;
};

Once the structure template is defined, a variable of that type is declared like any built-in type, struct student st;. An individual member is reached through the dot operator (.), for example st.roll, and a structure variable can be initialized at declaration in the same order as its members, struct student st = {"Sonia", 23, 1450.50};. Compared with an array, which groups elements of the same type, a structure groups elements that may all be different types, and can therefore model a real-world record, such as one student's name, roll number and fee, far more directly than a plain array could.

What this unit covers

  • Introduction
  • Array of structure
  • Passing structure to function
  • Passing array of structure to function
  • Structure within structure (Nested Structure)
  • Union
  • Pointer to structure

Array of structure

2081 · 5 marks

Create a structure called STUDENT with data members SID, name, address, CGPA. Write a program to initialize the value of 100 students and display the information of those students whose address is "KTM" and CGPA is between 3.5 to 4. [5]

--- Part Description ------------------- struct STUDENT Defines the structure with members SID, name, address, CGPA struct STUDENT st[100] Declares an array of structures to hold 100 student records First for loop Reads and initializes data for all 100 students using scanf strcmp(st[i].address, "...

Open this answer on its own page →

2080 · 10 marks

Differentiate between source code and object code.Create a structure named Book which remembers Book_Name, Price and Author. Then, make the list of top 10 records of book and print the name of authors having the price of book greater than 1000.[3+7]

Show solved answer

Answer

(a) Difference Between Source Code and Object Code

BasisSource CodeObject Code
DefinitionThe program written by a programmer in a high-level language (e.g., C) that is human-readableThe machine-level code generated by the compiler after translating the source code
ReadabilityEasily readable and understandable by humansNot directly readable by humans; consists of binary/machine instructions
File ExtensionStored as .c (in C language)Stored as .obj or .o file
ProcessingCannot be directly executed by the CPUPassed to the linker to produce an executable file
Error DetectionSyntax errors are detected at this stage during compilationNo syntax errors; errors at this stage are linking errors
GenerationWritten manually by the programmerAutomatically generated by the compiler

Flow (from notes):

source.c --> Compiler --> source.obj --> Linker --> source.exe --> Output

(b) Structure Book with Top 10 Records

Problem Analysis

  • Define a structure Book with fields: Book_Name, Price, Author
  • Store 10 book records
  • Print the names of authors whose book price is greater than 1000

Program

#include <stdio.h>
#include <conio.h>

/* Define the structure Book */
struct Book {
    char Book_Name[50];
    float Price;
    char Author[50];
};

void main() {
    int i;

    /* Declare an array of 10 Book structures */
    struct Book books[10];

    clrscr();

    /* Input 10 book records */
    printf("Enter details of 10 books:\n");
    for (i = 0; i < 10; i++) {
        printf("\n--- Book %d ---\n", i + 1);

        printf("Enter Book Name  : ");
        scanf(" %[^\n]", books[i].Book_Name);

        printf("Enter Author Name: ");
        scanf(" %[^\n]", books[i].Author);

        printf("Enter Price      : ");
        scanf("%f", &books[i].Price);
    }

    /* Print authors whose book price is greater than 1000 */
    printf("\n\nAuthors with Book Price greater than 1000:\n");
    printf("--------------------------------------------\n");

    for (i = 0; i < 10; i++) {
        if (books[i].Price > 1000) {
            printf("Author: %s  |  Book: %s  |  Price: %.2f\n",
                   books[i].Author,
                   books[i].Book_Name,
                   books[i].Price);
        }
    }

    getch();
}

Sample Output

Enter details of 10 books:

--- Book 1 ---
Enter Book Name  : Let Us C
Enter Author Name: Yashavant Kanetkar
Enter Price      : 850

--- Book 2 ---
Enter Book Name  : The C Programming Language
Enter Author Name: Dennis Ritchie
Enter Price      : 1200

--- Book 3 ---
Enter Book Name  : Data Structures
Enter Author Name: Seymour Lipschutz
Enter Price      : 1500
...

Authors with Book Price greater than 1000:
--------------------------------------------
Author: Dennis Ritchie   |  Book: The C Programming Language  |  Price: 1200.00
Author: Seymour Lipschutz|  Book: Data Structures             |  Price: 1500.00

Explanation of Key Steps

  1. Structure Declaration: struct Book is defined with three members:

    • Book_Name[50] -- stores the title
    • Price -- stores the price as float
    • Author[50] -- stores the author name
  2. Array of Structures: struct Book books[10] creates a list of 10 book records.

  3. Input Loop: A for loop runs from i = 0 to i < 10 to accept all 10 records using scanf.

  4. Condition Check: A second for loop checks if (books[i].Price > 1000) and prints the author name if the condition is true.

Open this answer on its own page →

2079 · 5 marks

Create a structure 'Employee' having Name, Address, Salary, and Age as member functions. Display the name of the employee having age between 40 and 50 and are living in Kathmandu. [5]

Concept Description ------ struct Employee Defines the structure with 4 members emp[100] Array of structure to store multiple employees strcmp() Compares Address string with "Kathmandu" (returns 0 if equal) Age = 40 && Age <= 50 Checks if age falls in the required range Both conditions joined by ...

Open this answer on its own page →

2077 · 10 marks

What is structure?How is it different from union?Create a structure named course with name, code and credit_hour as its member.Write a program using this structure to read data of 5 courses and display data of those courses with credit_hour greater than 3.[1+2+2+5]

Show solved answer

Structure in C: Definition, Difference from Union, and Program


1. What is a Structure? [1 mark]

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

2. Difference Between Structure and Union [2 marks]

FeatureStructureUnion
Keywordstructunion
Memory AllocationEach member gets its own separate memoryAll members share the same memory
Total SizeSum of sizes of all membersSize of the largest member only
AccessAll members can be accessed and used simultaneouslyOnly one member can hold a value at a time
UsageWhen all members are needed at the same timeWhen only one member is needed at a time (saves memory)

Example:

struct S { int a; float b; };   // size = sizeof(int) + sizeof(float) = 6 bytes
union U  { int a; float b; };   // size = sizeof(float) = 4 bytes (largest member)

3. Structure Named course with Members [2 marks]

struct course {
    char name[50];
    char code[10];
    int credit_hour;
};
  • name stores the course name
  • code stores the course code
  • credit_hour stores the number of credit hours

4. Complete Program: Read 5 Courses and Display Those with credit_hour > 3 [5 marks]

#include<stdio.h>
#include<conio.h>

struct course {
    char name[50];
    char code[10];
    int credit_hour;
};

void main() {
    struct course c[5];
    int i;
    clrscr();

    /* Reading data for 5 courses */
    for(i = 0; i < 5; i++) {
        printf("\nEnter details for Course %d:\n", i + 1);

        printf("Enter Course Name: ");
        scanf("%s", c[i].name);

        printf("Enter Course Code: ");
        scanf("%s", c[i].code);

        printf("Enter Credit Hour: ");
        scanf("%d", &c[i].credit_hour);
    }

    /* Displaying courses with credit_hour greater than 3 */
    printf("\n\nCourses with Credit Hour greater than 3:\n");
    printf("------------------------------------------\n");
    printf("Name\t\tCode\t\tCredit Hour\n");
    printf("------------------------------------------\n");

    for(i = 0; i < 5; i++) {
        if(c[i].credit_hour > 3) {
            printf("%s\t\t%s\t\t%d\n", c[i].name, c[i].code, c[i].credit_hour);
        }
    }

    getch();
}

Sample Output:

Enter details for Course 1:
Enter Course Name: Mathematics
Enter Course Code: MTH101
Enter Credit Hour: 3

Enter details for Course 2:
Enter Course Name: Physics
Enter Course Code: PHY101
Enter Credit Hour: 4

Enter details for Course 3:
Enter Course Name: C_Programming
Enter Course Code: CSC101
Enter Credit Hour: 5
...

Courses with Credit Hour greater than 3:
------------------------------------------
Name            Code            Credit Hour
------------------------------------------
Physics         PHY101          4
C_Programming   CSC101          5

Key Points:

  • struct course c[5] declares an array of structures to hold data of 5 courses.
  • The dot operator (.) is used to access structure members (e.g., c[i].name).
  • A for loop reads data for all 5 courses.
  • A second for loop with an if condition filters and displays only those courses where credit_hour > 3.
Open this answer on its own page →

Union

2079 · 5 marks

What is the advantage of the union over structure? List any four string library functions with the prototype. [5]

The primary advantage of union over structure is memory efficiency. In a structure, each member is allocated its own separate memory space, so the total memory used is the sum of all members' sizes. In a union, all members share the same memory location. The compiler allocates memory equal to the...

Open this answer on its own page →

Structure within structure

2078 · 10 marks

Define structure.Explain nested structure with example.Create a structure named book with name, author, and publisher as its members.Write a program using this structure to read data of 50 books and display name of those books published by 'XXX' publisher.[1+2+2+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. Syntax: --- A nested structure is a structure that contains another structure as one of its members. That i...

Open this answer on its own page →

Introduction

2075 · 5 marks

What is structure? Create a structure rectangle with data members length and breath. [2+3]

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: - The definition starts with the keyword struct followed by a tag name (structure name). - After the st...

Open this answer on its own page →

2074 · 10 marks

What is the structure? How is it different from array? Create a structure student having data members name, roll number and percentage.Complete the program to display the name of student having percentage greater than or equal to 60.[5+5]

--- (a) What is a 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 data member. Feature Array Structure --------- Data Type Stores elements of the same data...

Open this answer on its own page →