0% found this document useful (0 votes)
13 views37 pages

C Structures: Definitions and Examples

This document covers various aspects of structures in C, including nested structures, pointers, arrays of structures, and dynamic memory allocation. It explains how to define and use structures, access their members, and the differences between arrays and structures. Additionally, it provides example programs demonstrating these concepts and discusses the importance of dynamic memory allocation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views37 pages

C Structures: Definitions and Examples

This document covers various aspects of structures in C, including nested structures, pointers, arrays of structures, and dynamic memory allocation. It explains how to define and use structures, access their members, and the differences between arrays and structures. Additionally, it provides example programs demonstrating these concepts and discusses the importance of dynamic memory allocation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT IV STRUCTURES

Structure - Nested structures – Pointer and Structures – Array of structures – Example Program using
structures and pointers – Self referential structures – Dynamic memory allocation - Singly linked list -
typedef.

Structure Definition :

A structure in C is that allows you to combine multiple variables of different data types under a single name.

Example:
Student: name, roll no, mark, avg
Book: author, title, price, year
Address: door no, street name, place, state, pin
Difference b/w Arrays and Structures:

Arrays Structures
Collection of similar data types. Collection of different data types.
Static memory allocation is done in arrays Dynamic memoryallocation is done in structures.
It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to
an array element. access members of structures
Array is a pointer to its first element. Structure is not a pointer.
Array is a derived data type. Structure is a user defined data type.
Accessing array element takes less time Accessing structure member takes more time.
It has no keywords. It uses keyword “struct”

Structure Definition

Structure definition means creating a new user-defined datatype using the keyword `struct` to group
different data types. Note: semicolon }; in the ending line is must.

Steps :
1. Declaring structure
2. Declaring structure variable
3. Initializing the members of the structure
4. Accessing the members of structure
1. Declaring structure:

Syntax: Example:
struct tag_name struct student
{ {
datatype member 1; char name[10];
datatype member 2; int roll_no;
float percentage;

datatype member n; };
};

2. Structure Declaration

2. Declaring structure variable


Syntax: Example:
struct tag_name
{ struct student
datatype member 1; {
datatype member 2; char name[10];
datatype member 3; int roll_no;
‘ float percentage;
‘ }
struct book s1,s2;
datatype member n;
} variable1, variable2,……. variable n; Note:
Structure variable can be declared within the
structure definition or in the main function.
[Link] the members of structure:
Initialization can be done in 2 ways.
❖ Compile time initialization:
- uses assignment operator(=) to initialize values to the members of structure.
Example:
struct student s1={“ramya”,1001,45.8};
struct student s2={“anitha”,1002,89.6};
❖ Run time initialization:
- uses scanf function to read the input from the user.
Example:
printf("enter s1 student details");
scanf("%s%d%f",[Link],&s1.roll_no,&[Link]);

printf("enter s2 student details");


scanf("%s%d%f",[Link],&s2.roll_no,&[Link]);
4. Accessing the members of the structure:
- Members can be accessed using .operator (dot). Also pointer operator is used(->)
Syntax:
structure_variable_name . member_name;
Example:
[Link] // to access name of s1
[Link] // to access percentage of s2

Program to print student details( accessing member using .dot Output:


operator): Enter rollno, name , percentage
#include<stdio.h> 1001
struct student ramya
{ 96.8
int roll; Student details are:
char name[10]; ROLL_NO=1001 NAME=ramya
float percentage; PERCENTAGE=96.80000
}s1;
int main()
{
printf("Enter rollno, name , percentage\n");
scanf("%d%s%f", &[Link], [Link], &[Link]);
printf("Student details are:\n");
printf ("ROLL_NO=%d\n NAME=%s\n PERCENTAGE=%f\n",
[Link], [Link], [Link]);
return(0);
}

NESTED STRUCTURE:
Definition
● A nested structure is a structure that contains another structure as its member. It is used when
one record has another record inside it. which means A structure with in a structure is
called nested structure.
● The elements of nested structure are accessed using dot (.) operator

Why Nested Structure

● To represent complex data


● To group related information inside another structure
● Makes the program organized and readable

Important Points (Write These in Notes):

1. A structure can be declared inside another structure.

2. A nested structure is accessed using the dot operator multiple times.

3. Memory is allocated when the outer structure variable is created, including memory for the inner
structure.

4. Nested structures help represent real-world objects.

Example: Student → Address


Employee → Date of Joining

Book → Publication Details

5. Inner structure must be defined before using it in outer structure.

Simple Example Program

Syntax #include <stdio.h>

#include <string.h>

struct Inner {

data_type a; struct Address {

data_type b; char city[20];

}; int pincode;

struct Outer { };

data_type member1; struct Student {

struct Inner obj; char name[20];

}; int id;

struct Address addr; // nested structure

};

int main() {

struct Student s = {"Ravi", 101, {"Chennai",


600001}};

printf("%s\n", [Link]);

printf("%d\n", [Link]);

printf("%s\n", [Link]);

printf("%d\n", [Link]);

return 0;

Output:
Ravi

101

Chennai

600001

Syntax:
structure tagname_1 Example:
{ struct Employee
data_type member1; {
data_type member2; char ename[20];
data_type member3; int empid;
.. int salary;
member n; struct date
structure tagname_2 {
{ int day;
data_type member_1; int month;
data_type member_2; int year;
data_type member_3; }doj;
... }emp;
member_n;
} var1; Syntax:
} var2;
outrstructurevariable . innerstructure variable .
innerstructuremember

To Access the Nested members,

Accessing month Field : [Link]

Accessing day Field : [Link]

Accessing year Field : [Link]

Program to display employee details using Output:


nested structure:
#include <stdio.h> Employee Name : ramya
struct Employee
{ Employee ID : 1001
char ename[20];
int empid; Employee Salary : 25000
int salary;
struct date
{ Employee DOJ : 25/9/1988
int day;
int month;
int year;
}doj;
}emp;
int main()
{
struct Employee emp={"ramya",1001,25000,
{25,9,1988}};
printf("\nEmployee Name : %s",[Link]);
printf("\nEmployee ID : %d",[Link]);
printf("\nEmployee Salary : %d",[Link]);
printf("\nEmployee DOJ : %d/%d/%d",
[Link], [Link], [Link]);
return 0;
}

ARRAY OF STRUCTURES:

Definition:

● An array of structures is a collection of structure variables stored in a continuous memory


block.
● It allows you to store multiple records of the same structure type.

Example:

* Multiple students
* Multiple employees
* Multiple books

Why Use Array of Structures?


* To store many records together
* To access them using index numbers
* To process large sets of structured data easily
Syntax:

struct StructureName {

data_type member1;

data_type member2;

};

struct StructureName arrayName[size];

Program to print 5 student details using array Enter details of student 1


of structures:

#include<stdio.h>
Enter name: Ravi
struct student
Enter roll no: 101
{
Enter marks: 89.5
char name[20];

int roll_no, i;
Enter details of student 2
float marks;

};
Enter name: Kavi
int main()
Enter roll no: 102
{
Enter marks: 92.0
struct student s[5];

int i;
Enter details of student 3
for(i = 0; i <5; i++)

{
Enter name: Mani
printf("\n Enter details of student %d\n\n",
i+1); Enter roll no: 103
Enter marks: 88.0

printf("Enter name: ");

scanf("%s", s[i].name); Enter details of student 4

printf("Enter roll no: "); Enter name: Sara

scanf("%d", &s[i].roll_no); Enter roll no: 104

Enter marks: 91.0

printf("Enter marks: ");

scanf("%f", &s[i].marks); Enter details of student 5

Enter name: Kumar

printf("\n"); Enter roll no: 105

printf("Name\tRoll no\tMarks\n"); Enter marks: 87.0

for(i = 0; i < 5; i++ )

{ Name Roll no Marks

printf("%s\t%d\t%.2f\n", Ravi 101 89.50

s[i].name, s[i].roll_no, s[i].marks); Kavi 102 92.00

} Mani 103 88.00

return 0; Sara 104 91.00

} Kumar 105 87.00

Array Initializaton Program

#include <stdio.h> 101 Ravi 89.50

102 Kavi 92.00

struct Student { 103 Mani 88.00

int roll;

char name[20];
float marks;

};

int main() {

struct Student s[3] = {

{101, "Ravi", 89.5},

{102, "Kavi", 92.0},

{103, "Mani", 88.0}

};

for (int i = 0; i < 3; i++) {

printf("%d %s %.2f\n", s[i].roll, s[i].name,


s[i].marks);

return 0;

How To Find the Size of Structure?


- sizeof() function is used to find the size of structure.
- sizeof can be applied to any data-type, including primitive types such as integer and floating-
point types, pointer types, or compound datatypes such as Structure, union [Link]:
Example: (Sizeof() for structure)
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
};
int main()
{
printf("Size of book structure is :%d",sizeof([Link]));
}
Output:
Size of book structure is :84

POINTER AND STRUCTURE:


Definition

● A pointer to a structure is a pointer variable that stores the address of a structure variable.
● It is used to access structure members through a pointer using the arrow operator (`->`).

Why Use Structure Pointer?

* To pass structures to functions efficiently


* To avoid copying large structure data
* To dynamically allocate structures using `malloc()`
* To access structure members using pointer syntax
Important Points (Write These in Notes)
1. Structure pointer stores the address of structure variable.

2. Arrow operator (`->`) is used to access members.

3. `ptr->member` is same as `(*ptr).member`.

Declaring a Pointer to a Structure:

struct Student s;

struct Student *ptr;

ptr = &s; // ptr stores address of s

Accessing Structure Members Using Pointer

Two ways:

1. Using `(*ptr).member`

(*ptr).roll

(*ptr).marks

2. Using Arrow Operator (`->`) (Recommended)

ptr->roll

ptr->name

ptr->marks

Example Program (Simple & Important) Output


#include <stdio.h>

#include <string.h>

struct Student { Roll = 101

int roll; Name = Ravi

char name[20]; Marks = 89.50

float marks;

};

int main() {

struct Student s = {101, "Ravi", 89.5};

struct Student *ptr;

ptr = &s;

printf("Roll = %d\n", ptr->roll);

printf("Name = %s\n", ptr->name);

printf("Marks = %.2f\n", ptr->marks);

return 0;

Dynamic Memory Allocation with Structure Pointer (Very Important)

#include <stdio.h> Output:

#include <stdlib.h> 101 95.50

struct Student {

int roll;

float marks;

};

int main() {

struct Student *p;


p = (struct Student*) malloc(sizeof(struct
Student));

p->roll = 101;

p->marks = 95.5;

printf("%d %.2f", p->roll, p->marks);

return 0;

ARRAY OF STRUCTURES USING POINTERS – NOTES

Definition

A pointer to an array of structures is used when we want to access structure elements using pointers
instead of normal array indexing.

Why Use Pointer with Array of Structures?

* To move through the array using pointer arithmetic

* Useful in dynamic arrays

* Faster access

* Helpful in linked list, trees, and dynamic allocation

Syntax

struct Student s[5];

struct Student *p;

p = s; // Equivalent to p = &s[0]

Example Program (Very Important)

#include <stdio.h> Output

101 89.50

struct Student { 102 92.00

int roll; 103 88.00


float marks;

};

int main() {

struct Student s[3] = {

{101, 89.5},

{102, 92.0},

{103, 88.0}

};

struct Student *p = s; // p points to s[0]

for (int i = 0; i < 3; i++) {

printf("%d %.2f\n", (p + i)->roll, (p + i)-


>marks);

return 0;

Array of Pointers to Structure


Concept (Very Simple)

o You create several structure variables


o Then create an array that stores addresses of those structures
o Access members using `ptr[i]->member`
o Program: Array of Pointers to Structure

#include <stdio.h> Output

struct Student { Roll Marks


int roll; 101 89.50

float marks; 102 91.00

}; 103 88.00

int main() {
struct Student s1 = {101, 89.5};
struct Student s2 = {102, 91.0};
struct Student s3 = {103, 88.0};

struct Student *ptr[3]; // array of pointer


to structure

ptr[0] = &s1;
ptr[1] = &s2;
ptr[2] = &s3;

printf("Roll\tMarks\n");

for (int i = 0; i < 3; i++) {


printf("%d\t%.2f\n", ptr[i]->roll, ptr[i]-
>marks);
}

return 0;
}

DYNAMIC MEMORY ALLOCATION

Dynamic Memory Allocation (DMA) in C allows you to allocate memory at runtime, not at compile time.

C provides four main library functions for DMA:

* malloc → garbage

* calloc → zero initialized

* realloc → resize

* free → release memory

* Avoid memory leaks

* Always check for NULL

Why Dynamic Memory Allocation?

✔ When size is unknown at compile time


✔ Efficient memory usage

✔ Dynamic data structures (Linked List, Stack, Queue, Tree)

These functions are available in:

#include <stdlib.h>

1. malloc() – Memory Allocation

Allocates single block of memory.

Syntax

ptr = (type*) malloc(size_in_bytes);

Features

* Allocates memory but does NOT initialize, garbage values inside.

* Returns `NULL` if memory not available.

* Faster than calloc.

Example

int *p = (int*) malloc(5 * sizeof(int));

#include <stdio.h> How many numbers? 3

#include <stdlib.h> Enter 3 numbers:

int main() { 10

int n, *p; 20

30

printf("How many numbers? ");

scanf("%d", &n); You entered:

10 20 30

// Allocate memory for n integers

p = (int*) malloc(n * sizeof(int));

printf("Enter %d numbers:\n", n);

for (int i = 0; i < n; i++) {


scanf("%d", &p[i]); // store values

printf("\nYou entered:\n");

for (int i = 0; i < n; i++) {

printf("%d ", p[i]); // print values

free(p); // release memory

return 0;

2. calloc() – Contiguous Allocation

Purpose

Allocates multiple blocks, initializes all to 0.

Syntax

ptr = (type*) calloc(n, size_in_bytes);

Features

* Memory initialized to 0

* Slower than malloc

Example

int *p = (int*) calloc(5, sizeof(int));

#include <stdio.h> How many numbers? 3

#include <stdlib.h> Enter 3 numbers:

int main() { 10
int n, *p; 15

printf("How many numbers? "); You entered:

scanf("%d", &n); 5 10 15

// Allocate memory using calloc

p = (int*) calloc(n, sizeof(int));

printf("Enter %d numbers:\n", n);

for (int i = 0; i < n; i++) {

scanf("%d", &p[i]);

printf("\nYou entered:\n");

for (int i = 0; i < n; i++) {

printf("%d ", p[i]);

free(p);

return 0;

3. realloc() – Reallocation

Purpose

Changes the size of already allocated memory.

Syntax

ptr = (type*) realloc(ptr, new_size);

Features
* Used to increase or decrease memory size

* Old values retained

* May move memory block to a new location

Example

p = (int*) realloc(p, 10 * sizeof(int));

#include <stdio.h> 10 20 30 40

#include <stdlib.h>

int main() {

int *p;

// allocate memory for 2 integers

p = (int*) malloc(2 * sizeof(int));

p[0] = 10;

p[1] = 20;

// increase size to 4 integers

p = (int*) realloc(p, 4 * sizeof(int));

p[2] = 30;

p[3] = 40;

for (int i = 0; i < 4; i++) {

printf("%d ", p[i]);

free(p);

return 0;

}
4. free() – Release memory

Purpose

Frees dynamically allocated memory.

Syntax

free(ptr);

Features

* Prevents memory leak

* Should always be used after malloc/calloc/realloc

C Program to generate Salary Slip of employee( Dynamic memory allocation for Structure
using pointers):
#include <stdio.h> Output:
#include<stdlib.h> enter the number of employee2
struct employee enter the nameravi
{ Enter Basic Salary (RS): 12000
char name[10];
int basic, da, hra, ta, others; Enter Hra1000
int pf,it,t;
int net_salary; Enter da500
}e[10];
int main() Enter TA500
{
int i,n; Enter Others1000
struct employee *ptr;
printf("enter the number of employee"); Enter pf500
scanf("%d",&n);
ptr=(struct employee*)malloc(n * sizeof(struct Enter IT1000
employee)); enter the nameraja
for(i=0;i<n;i++) Enter Basic Salary (RS): 25000
{
printf("enter the name"); Enter Hra1000
scanf("%s",(ptr+i)->name);
printf("Enter Basic Salary (RS): "); Enter da1000
scanf("%d",&(ptr+i)->basic);
printf("\nEnter Hra"); Enter TA1000
scanf("%d",&(ptr+i)->hra);
printf("\nEnter da"); Enter Others500
scanf("%d",&(ptr+i)->da);
printf("\n Enter TA"); Enter pf1000
scanf("%d",&(ptr+i)->ta);
printf("\nEnter Others"); Enter IT1500
scanf("%d",&(ptr+i)->others);
printf("\nEnter pf"); Name is ravi Net Salary is:RS
scanf("%d",&(ptr+i)->pf); 13500
printf("\nEnter IT");
scanf("%d",&(ptr+i)->it); Name is raja Net Salary is:RS
26000
//calculate net salary
(ptr+i)->net_salary = (ptr+i)->basic + (ptr+i)->da +
(ptr+i)->hra + (ptr+i)->ta + (ptr+i)->others - ((ptr+i)->pf+(ptr+i)-
>it);
}
//printing Net salary
for(i=0;i<n;i++)
{
printf("\n Name is %s",(ptr+i)->name);
printf("\t Net Salary is:RS %d\n",(ptr+i)->net_salary);
}
return(0);
}

SELF REFERENTIAL STRUCTURES:


Definition
A self-referential structure is a structure that contains a pointer to the same structure type inside it.
✔ Used in linked lists, trees, stacks, queues
✔ Structure contains pointer to another object of its own type
General Syntax

struct Node {
int data;
struct Node *next; // pointer to same structure type
};
* `next` can store the address of another Node
* This creates a chain of nodes → Linked list
Key Points
o A structure CANNOT contain a variable of same type (infinite size)
o But it CAN contain a pointer to same type (fixed size)

struct Node {
int x;
struct Node *next; // ok (pointer has fixed size)
};
#include <stdio.h> Output
struct Node {

int data; First node data: 10

struct Node *next; // self-referential pointer Second node data: 20

};

int main() {

struct Node n1, n2;

[Link] = 10;

[Link] = 20;

[Link] = &n2; // link n1 → n2

[Link] = NULL; // end of list

printf("First node data: %d\n", [Link]);

printf("Second node data: %d\n", [Link]-


>data);

return 0;

LINKED LIST

A Linked List is a dynamic data structure made of nodes, where each node contains:
1. Data
2. Pointer to the next node

Unlike arrays, linked lists are not stored in continuous memory.


Why Linked List? (Advantages)
✔ Dynamic size (can grow/shrink at runtime)
✔ No memory wastage
✔ Easy insertion & deletion (O(1) at beginning)
✔ Efficient memory usage
Disadvantages
❌ No random access → must traverse from beginning
❌ Extra memory for pointer
❌ Slower access than arrays

Types of Linked Lists


1. Singly Linked List
2. Doubly Linked List
3. Circular Linked List
4. Circular Doubly Linked List
Singly Linked List
Each node points to the next node.
[10] → [20] → [30] → NULL

o Head pointer points to the first node.

o Basic Operations on Linked List


[Link]
* Insert at beginning

* Insert at end

* Insert at any position

[Link]
* Delete first node
* Delete last node
* Delete specific value
* Delete at position
[Link]
Print all nodes one-by-one.
Node Creation:
#include <stdio.h> Linked List: 10 -> 20 -> 30 -> NULL

#include <stdlib.h>

struct node {

int data;

struct node *next;

};

int main() {

struct node *head, *second, *third;

// Allocate memory for nodes

head = (struct node*)malloc(sizeof(struct


node));

second = (struct node*)malloc(sizeof(struct


node));

third = (struct node*)malloc(sizeof(struct


node));

// Assign data

head->data = 10;

second->data = 20;

third->data = 30;
// Link nodes

head->next = second;

second->next = third;

third->next = NULL;

// Print linked list

struct node *temp = head;

printf("Linked List: ");

while(temp != NULL) {

printf("%d -> ", temp->data);

temp = temp->next;

printf("NULL\n");

// Free memory

free(head);

free(second);

free(third);

return 0;

Simple Traversal Program


void display(struct Node *head) {
struct Node *temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
Insert at Beginning (Simple)
struct Node* insertBegin(struct Node *head, int value) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = head;
return newNode;
}
Insert at End
void insertEnd(int x) {
struct node *n = malloc(sizeof(struct node));
n->data = x;
n->next = NULL;

Delete First Node


// First node delete 10 -> 20 -> 30 -> NULL

if(head->data == value) { temp = head;

temp = head; temp ---> [10]

head = head->next; head ---> [10]

free(temp); head = head->next;

} head ---> [20]

// Middle/last delete temp ---> [10]

prev->next = temp->next; free(temp);🡪free(10) means deleted

free(temp); 20 -> 30 -> NULL

Reverse Linked List


void reverseList(struct node **head) { 10 -> 20 -> 30 -> NULL

struct node *prev = NULL, *current = *head, next = current->next;


*next = NULL;
current = 10
while (current != NULL) {
next = 20
next = current->next; // store next
current->next = prev;
current->next = prev; // link reverse
prev = current; // move prev 10->next = NULL

current = next; // move current prev = current; now current 10

} prev = 10;

*head = prev; // new head current = next; now next 20

} current = 20

prev = 10 -> NULL

current = 20 -> 30 -> NULL

Second iteration

Next=30

20-> Next=10

Prev=20

Current=30 loop Repeated

30->20->10-null

Real-World Use Cases


✔ Undo/Redo (text editors)
✔ Music playlist navigation
✔ Memory allocation strategies
✔ Graphs & Trees
✔ Queue in OS scheduling
Difference: Array vs Linked List
Array Linked List

Fixed size Dynamic size

Continuous memory Non-continuous

| Fast access O(1) Slow access O(n)

Hard insertion Easy insertion

Doubly Linked List


Circular Linked List

TYPEDEF
Definition
`typedef` is used in C to give a new name (alias) to an existing data type.
* Makes code easier to read
* Reduces typing for complex types
* Commonly used with **structures, pointers, arrays, function pointers
Syntax
typedef existing_type new_name;

* `existing_type` → int, float, struct, etc.


* `new_name` → the new type name

. With Structures
#include <stdio.h> 101 Ravi

typedef struct {

int roll;

char name[20];

} Student;

int main() {

Student s1 = {101, "Ravi"};


printf("%d %s", [Link], [Link]);

return 0;

Example Programs Using Pointer and Structure:

1.C program to read, display, add, and Enter first distance (km m): 5 800
subtract two distances. Distance must
bedefined using kms and meters using Enter second distance (km m): 3 500
structures.(typedef)

#include <stdio.h> Sum: 9 km 300 m

Difference: 2 km 300 m
typedef struct {

int km;

int m;

} Distance;

int main() {

Distance d1, d2, sum, diff;

// Read distances

printf("Enter first distance (km m): ");

scanf("%d %d", &[Link], &d1.m);

printf("Enter second distance (km m): ");

scanf("%d %d", &[Link], &d2.m);

// Addition
[Link] = [Link] + [Link];

sum.m = d1.m + d2.m;

if (sum.m >= 1000) { // handle meter


overflow

[Link] = [Link] + 1;

sum.m = sum.m - 1000;

// Subtraction

[Link] = [Link] - [Link];

diff.m = d1.m - d2.m;

if (diff.m < 0) { // borrow 1 km if


meters negative

[Link] = [Link] - 1;

diff.m = diff.m + 1000;

// Display

printf("\nSum: %d km %d m\n", [Link],


sum.m);

printf("Difference: %d km %d m\n", [Link],


diff.m);

return 0;

2.C program to add, subtract two complex OUTPUT


numbers using structure.

#include <stdio.h> Enter first complex (real imag): 3 4


Enter second complex (real imag): 1 2

struct Complex { float real, imag; }; Sum = 4.0 + 6.0i

Diff = 2.0 + 2.0i

int main() {

struct Complex c1, c2, sum, diff;

printf("Enter first complex (real imag): ");

scanf("%f %f", &[Link], &[Link]);

printf("Enter second complex (real imag): ");

scanf("%f %f", &[Link], &[Link]);

[Link] = [Link] + [Link];

[Link] = [Link] + [Link];

[Link] = [Link] - [Link];

[Link] = [Link] - [Link];

printf("Sum = %.1f + %.1fi\n", [Link],


[Link]);

printf("Diff = %.1f + %.1fi\n", [Link],


[Link]);

return 0;

Define Union. Describe how to declare, initialize and accessmembers of Union with a
programming example.
Definition of Union
A union is a user-defined data type in C that allows different variables to share the same memory
location.
At any time, only one member of a union can store a value.
Declaration of a Union
union Example {
int x;
float y;
char ch;
};
Creating (Declaring) Union Variable
union Example e;
Initializing Union
You can initialize a union only one member at a time:

When a new member is assigned, the previous value is overwritten because all members share the
same memory.

Accessing Union Members

Use the dot `.` operator with union variable:

printf("%d", e.x);
printf("%f", e.y);
printf("%c", [Link]);
Simple Program Example
#include <stdio.h> Output

union Data { ID = 101

int id; Marks = 88.5

float marks; Grade = A

char grade;

};

int main() {

union Data d;
[Link] = 101;

printf("ID = %d\n", [Link]);

[Link] = 88.5; // overwrites id

printf("Marks = %.1f\n", [Link]);

[Link] = 'A'; // overwrites marks

printf("Grade = %c\n", [Link]);

return 0;

(ii)Illustrate a C program to store the employee information using Structure and search a
particular employee details.
#include <stdio.h>

#include <string.h>

struct Employee {

int id;

char name[30];

float salary;

};

int main() {

struct Employee e[50]; // store up to 50


employees
int n, i, searchId, found = 0;

// Get number of employees

printf("Enter number of employees: ");

scanf("%d", &n);

// Reading employee details

for(i = 0; i < n; i++) {

printf("\nEnter details of employee %d\n",


i+1);

printf("ID: ");

scanf("%d", &e[i].id);

printf("Name: ");

scanf("%s", e[i].name);

printf("Salary: ");

scanf("%f", &e[i].salary);

// Search operation

printf("\nEnter Employee ID to search: ");

scanf("%d", &searchId);

for(i = 0; i < n; i++) {


if(e[i].id == searchId) {

found = 1;

printf("\nEmployee Found!\n");

printf("ID : %d\n", e[i].id);

printf("Name : %s\n", e[i].name);

printf("Salary : %.2f\n", e[i].salary);

break;

if(!found)

printf("\nEmployee with ID %d not


found.\n", searchId);

return 0;

Explain passing structures to a function with respect to the following:


(i). Passing individual members.
(ii). Passing entire structure.
Passing Structures to a Function
We can pass structure information to a function in two ways:
i) Passing Individual Members
In this method, we do NOT pass the structure.
We pass only the required members of the structure (like int, float, char).
Example Code
#include <stdio.h>

struct Student {
int roll;
float marks;
};

void display(int r, float m) {


printf("Roll = %d\n", r);
printf("Marks = %.2f\n", m);
}

int main() {
struct Student s = {101, 89.5};

// Passing individual members


display([Link], [Link]);

return 0;
}

Explanation
* Function receives simple variables.
* Structure itself is not passed.
* Easy, but if many members → we must pass many arguments.

ii) Passing Entire Structure


Here, we pass the whole structure variable to a function.
Two ways:
1. Pass by value (copy sent)
2. Pass by reference using pointer (address sent)

Method A: Passing Entire Structure (by Value)


#include <stdio.h>

struct Student {
int roll;
float marks;
};

void display(struct Student s) {


printf("Roll = %d\n", [Link]);
printf("Marks = %.2f\n", [Link]);
}

int main() {
struct Student s1 = {101, 89.5};

// passing entire structure


display(s1);

return 0;
}
Explanation
* Full structure is passed.
* A copy is created inside the function.
* Changes inside function do NOT affect original structure.

Method B: Passing Structure Using Pointer (by Reference)

#include <stdio.h>

struct Student {
int roll;
float marks;
};

void display(struct Student *p) {


printf("Roll = %d\n", p->roll);
printf("Marks = %.2f\n", p->marks);
}

int main() {
struct Student s1 = {101, 89.5};

// passing address of structure


display(&s1);

return 0;
}

Examine the differences between nested structures and Array of structures.

Feature Nested Structures Array of Structures

Definition A structure inside another Multiple objects of the same


structure structure stored in an array.

Purpose To represent a complex object To store many records of the


that has another object inside same type.
it.

Structure relationship Shows a "has-a" relationship Shows a collection of similar


structure variables

Data organization Hierarchical Sequential (like list)

Usage Used when one unit has sub- Used when many units of
units. same type needed.

Example Employee HAS Address inside Many employees stored in an


it array.

Memory allocation Memory allocated for nested Memory allocated for each
structure inside parent element of array separately

Accessing [Link]` (dot emp[i].name` (indexing + dot).


chaining)

Flexibility Good for complex, multi-level Good for large sets of simple,
data. repetitive data.

Coding complexity Slightly complex & deep Simple & uniform.

You might also like