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.
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]
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 answerHide answer
Answer
(a) Difference Between Source Code and Object Code
| Basis | Source Code | Object Code |
|---|---|---|
| Definition | The program written by a programmer in a high-level language (e.g., C) that is human-readable | The machine-level code generated by the compiler after translating the source code |
| Readability | Easily readable and understandable by humans | Not directly readable by humans; consists of binary/machine instructions |
| File Extension | Stored as .c (in C language) | Stored as .obj or .o file |
| Processing | Cannot be directly executed by the CPU | Passed to the linker to produce an executable file |
| Error Detection | Syntax errors are detected at this stage during compilation | No syntax errors; errors at this stage are linking errors |
| Generation | Written manually by the programmer | Automatically 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
Bookwith 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
-
Structure Declaration:
struct Bookis defined with three members:Book_Name[50]-- stores the titlePrice-- stores the price as floatAuthor[50]-- stores the author name
-
Array of Structures:
struct Book books[10]creates a list of 10 book records. -
Input Loop: A
forloop runs fromi = 0toi < 10to accept all 10 records usingscanf. -
Condition Check: A second
forloop checksif (books[i].Price > 1000)and prints the author name if the condition is true.
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]
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 answerHide 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]
| Feature | Structure | Union |
|---|---|---|
| Keyword | struct | union |
| Memory Allocation | Each member gets its own separate memory | All members share the same memory |
| Total Size | Sum of sizes of all members | Size of the largest member only |
| Access | All members can be accessed and used simultaneously | Only one member can hold a value at a time |
| Usage | When all members are needed at the same time | When 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;
};
namestores the course namecodestores the course codecredit_hourstores 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
forloop reads data for all 5 courses. - A second
forloop with anifcondition filters and displays only those courses wherecredit_hour > 3.
Union
2079 · 5 marks
What is the advantage of the union over structure? List any four string library functions with the prototype. [5]
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]
Introduction
2075 · 5 marks
What is structure? Create a structure rectangle with data members length and breath. [2+3]
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]
Make Unit 8 stick
Practice CSC115 with flashcards & quizzes