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

Unit 4 PC Notes

Uploaded by

mathibm92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views37 pages

Unit 4 PC Notes

Uploaded by

mathibm92
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT – IV – STRUCTURE AND UNION

Structure - Nested structures – Pointer and Structures – Array of structures – Self referential
structures – Dynamic memory allocation - Singly linked list – typedef – Union - Storage classes and
Visibility.

4.1 Introduction
Array is a collection of elements of same type, but many times we have to store the
elements of different data types. The structure is a convenient way of grouping several
pieces of related information together.
Structure is a collection of different types of variables under single name.
4.2 Need for Structure Data Type
A variable stores a single value of a data type.
Arrays can store many values of similar data type.
In real life, we need to store values of different data types.
For Example, To maintain employee’s information we should have information such as their
name,age, qualification, salary etc.
Here, to maintain the information of employees, dissimilar data types are required.
For tackling such mixed data types, a special data type provided by C called structure .
Hence Structure is needed.
4.3 Structure Definition
A structure is a collection of variables of different data types, grouped together under
a single name.
Consider the data of student mark analysis: The data required are name, rollno marks, and
average. A structure data type called student can hold all this information:
struct student
{ char name[20];
int rollno;
int marks[8];
float avg;
};
The following are other examples for structure type

struct employee struct book


{ {
char name[20]; char name[30];
int empno; int pageno;
float salary; float price;
int exp ; };
};
4.4 Structure Declaration
The structure can be declared with the keyword struct following the name and opening brace
with data elements of different type, and then closing brace with semicolon.
Syntax:
struct structure_name struct structure_name
{ {
data_type variable 1; data_type variable 1;
data_type variable 2; data_type variable 2;
. (or) .
. .
data_type variable n; data_type variable n;
}v1,v2,….,vn; };
struct structure_name v1,v2,….,vn;

1
4.4.1 Rules for declaring a structure:
 A structure definition must end with a semicolon
 The structure appears at the top of the source program
 The structure variable must be accessed with dot(.) operator
 The structure can be declared with the keyword struct following the name and opening
brace with data elements of different type, then closing brace with semicolon.
 The individual structure elements are called as members.
 Name given to structure is called tag.
 Declaration of Structure reserves no space. It is nothing but the “Template / Map / Shape”
of the structure.
 Memory for structure variable is created, very first time when the variable is created.

4.4.2 Accessing structure elements:


 After declaring the structure type, variables, and members, the member of the structure can
be accessed by using the structure variable along with the dot (.) operator
Different Ways of Declaring Structure Variable and Accessing structure element
Way 1: Declaring structure Way 2: Declare Variables Way 3: Declaring Multiple
variable within the structure within the main function Structure Variables
definition itself
struct date struct date{ struct date
{ int day; {
int day; char month[20]; int day;
char month[20]; int year; char month[20];
int year; }; int year;
}today; main( ){ }yesterday, today, tomorrow;
struct date today;
}
For accessing the structure members for the above example
Structure name = date
Structure members are day, month, year
Structure variable = today
Syntax to access structure variable : structure_variable.member_name Eg: today.day , today.month ,
today.year
To get value for Structure variable:
scanf(“%d”, &today.day)
scanf(“%s”,today.month)
scanf(“%d”, &today.year)
To print values of Structure variable:
printf(“%d”, today.day)
printf(“%s”,today.month)
printf(“%d”, today.year)
4.5 Initialization of structure:
Initialization of Structure members:
1. Structure variable can be initialized in multiple ways:
Within structure definition
Declare and Initializing Single Variables Declare and Initializing Multiple Variables
struct student struct student{
{ char name [80];
char name [80]; int roll_no;
int roll_no; float marks ;
float marks ; } s1={“AAA”,54,469},
} s1={“AAA”,54,469}; s2={“BBB”,39,437};
2
Within main function
struct student struct student
{ {
char name [80]; char name [80];
int roll_no; int roll_no;
float marks ; float marks ;
} s1; } s1;
void main() void main()
{ {
struct student s1= {“AAA”,54,469}; struct student s1= {“AAA”,54,469};
-- struct student s2={“BBB”,39,437};
-- --
} }

Rules for initializing structure:


The individual data members of structure cannot be initialized.
The order of data members in a structure must match the order of values in enclosed
brackets.
We can initialize only some of the data members of the structure. The uninitializeddata
members can be initialized by default with zero (0) for int and float, ‘\0’ for character and
strings.
Structure variable can be initialized in compile time or run time
Exampe Program 1: To print the vehicle details using structure
#include<stdio.h>
struct vehicle
{
int wheels;
char vname[20];
char color[10];
} v1 = {4,"Nano","Red"};
void main()
{
printf(" \nNo of Wheels : %d",v1.wheels);
printf("\nVehicle Name : %s",v1.vname);
printf("\nVehicle Color : %s",v1.color);
}
Output
No of Wheels: 4
Vehicle Name: Nano
Vehicle Color: Red

Exampe Program 2 : To print student number, name, and marks using structure
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
int eng, phy, mat;
float avg;
}s;
3
void main(){
float total;
clrscr();
printf("Enter student details:\n");
printf("Enter student name:");
scanf("%s", s.name);
printf("Enter student roll no:");
scanf("%d",&s.rollno);
printf("Enter three subject mark:");
scanf("%d %d %d", &s.eng, &s.phy, &s.mat);
total=s.eng+s.phy+s.mat;
s.avg=total/3;
printf("\n Average of %s, Roll No:%d is %0.2f", s.name, s.rollno, s.avg);
getch();
}
Output:
Enter student details:
Enter student name : aaa
Enter student roll no : 1
Enter three subject mark : 90 80 75
Average of aaa, Roll No:1 is 81.67
4.6 Uses of Structure :
Structure allows grouping of different types of data
We can pass structure variable to a function like a normal variable
Complex data types can be handled by using nesting of structures
It is possible to create structure pointers
Structure provides flexibility to programmers to define own data types as per the
requirement
4.7 ARRAY OF STRUCTURES [or] Structure variable as array
A Structure is used to store the information of one particular object but if we need to store
more abjects such as 100 objects, then Array of Structure is used.
Example :
struct Bookinfo
{
char Name[20];
int Pages;
float Price;
}Book[100];
Explanation :
 Here Book structure is used to Store the information of one Book.
 In case if we need to store the Information of 100 books then Array of Structure isused.
 Book[0] stores the Information of 1st Book ,B[1] stores the information of 2nd Bookand So
on We can store the information of 100 books.
Book[3] is shown Below
Name Pages Price
Book [0]
Book [1]
Book [2]

Accessing member of Array of Structure:


The use of the period operator can be extended to arrays of structure by writing:
Structure_var [index].member_name
for example Accessing Pages field of Second Book : Book[1].pages
4
Example Program:
#include <stdio.h> #include<conio.h>
struct Bookinfo
{
char name[20];
int pages;
float price;
};
void main()
{
int i;
struct Bookinfo book[2];
for(i=0;i<2;i++)
{
printf("\nEnter the Name of Book : ");
scanf("%s",book[i].name);
printf("\nEnter the Number of Pages : ");
scanf("%d",&book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",&book[i].price);
}
printf("\n --------------Book Details ------------ ");
for(i=0;i<2;i++)
{
printf("\nName of Book : %s",book[i].name);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f",book[i].price);
}
getch();
}
Output
Enter the Name of Book : ABC
Enter the Number of Pages : 100
Enter the Price of Book : 200
Enter the Name of Book : EFG
Enter the Number of Pages : 200
Enter the Price of Book 300
----------------Book Details--------------
Name of Book: ABC
Number of Pages 100
Price of Book 200
Name of Book: EFG
Number of Pages 200
Price of Book 300

4.8 STRUCTURE WITHIN A STRUCTURE (OR) NESTED STRUCTURE


Structure written inside another structure is called as nested structures or Structure within
structure
We can write one Structure inside another structure or member of another structure.

5
Way 1 : Declaration of one structure within another
struct date
{
int date;
int month;
int year;
};
struct Employee
{
char ename[20];
int id;
float salary;
struct date doj;
}emp1;

Way 2 : Declaration of Embedded structures


struct Employee
{
char ename[20];
int id;
float salary;
struct date
{
int date;
int month;
}doj; int year;
}emp1;

Accessing Nested Elements:


Structure members are accessed using dot operator.
“date” structure is nested within Employee Structure.
Members of the “date” can be accessed using ‟employee”
emp1 & doj are two structure names (Variables)

Explanation of accessing elements in Nested Structure:


Accessing Month Field: emp1.doj.month
Accessing day Field: emp1.doj.day
Accessing year Field: emp1.doj.year
//Example Program for nested structure :
#include <stdio.h>
#include<conio.h>
struct details
{
char name[20];
int age;
char dob[10];
};
struct student{
struct details s1;
char roll_no[10];
float marks;
};
6
void main ()
{
struct student stu;
clrscr();
printf("Details of student: \n\n");
printf("Enter name: ");
scanf("%s", stu.s1.name);
printf("Enter age: ");
scanf("%d", &stu.s1.age);
printf("Enter dob: ");
scanf ("%s", stu.s1.dob);
printf("Enter roll no: ");
scanf("%s", &stu.roll_no);
printf("Enter Total marks: ");
scanf ("%f", &stu.marks);
printf("\n ........ \n\n");
printf("Name: %s\n", stu.s1.name);
printf("Age: %d\n", stu.s1.age);
printf("DOB: %s\n", stu.s1.dob);
printf("Roll no: %s\n", stu.roll_no);
printf("Total Marks: %.2f\n", stu.marks);
getch();
}

Output:
Details of student:
Enter name: aaa
Enter age: 19
Enter dob: 12/08/2003
Enter roll no: 101
Enter Total marks: 540
.....
Name: aaa
Age: 19
DOB: 12/08/2003
Roll no: 101
Marks: 540.00

4.9 POINTER TO STRUCTURES


Pointer to structure holds the address of the structure.
It is used to create complex data structures such as linked lists, trees, graphs and so on.
The members of the structure can be accessed using a special operator called as an arrow
operator( -> ).
Declaration :
Syntax : struct tagname *sptr;
Example : struct student *s
Accessing :
Syntax: Ptr-> membername;
Example: s->sno, s->sname, s->marks

7
// Example Program for pointer to Structure
#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char sname[30];
float marks;
};
void main ()
{
struct student s;
struct student *st;
clrscr();
printf("enter sno, sname, total marks:");
scanf ("%d%s%f", &s.sno, s.sname, &s. marks);
st = &s;
printf ("\nDetails of the student are\n");
printf ("Number = %d\n", st ->sno);
printf ("Name = %s\n", st->sname);
printf ("Marks =%f\n", st ->marks);
getch();
}
Output:
enter sno, sname, total marks:101 aaa 700
Details of the student are
Number = 101
Name = aaa
Marks =700.000000

4.10 Difference between structure and array


S.N Array Structure
O
1 Array is a collection of data items of same Structure is a collection of different types of
data type. variables under single name
2 Individual entries in a array are called Individual entries in a structure are called
elements. members.
3 Array elements are accessed by their position Structure members are accessed by their object
or subscript as dot (.) operator
4 No Keyword used for array The Keyword , struct is used
5 Elements of an array are stored in sequence Members of a structure are not stored in
of memory locations. sequence of memory locations.

8
Additional Programs based on Structure
1. Program To generate student mark sheets with subject details and the grades using structure
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
int m1,m2,m3,tot;
float avg;
}s[30];
void main()
{
int i, n;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Student %d details",i+1);
printf("\nEnter name:");
scanf("%s",s[i].name);
printf("Enter Rollno:");
scanf("%d",&s[i].rollno);
printf("Enter 3 subject marks:");
scanf("%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=0,s[i].avg=0.0;
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
}
printf("\t\t\tSTUDENTS MARK SHEET");
printf("\n\t\t ");
printf("\nName\tRollno\tMark1\tMark2\tMark3\tTotal\tAvg ");
for(i=0;i<n;i++)
printf("\n%s\t%d\t%d\t%d\t%d\t%d\t%f\t%c",s[i].name,s[i].rollno,s[i].m1,s[i].m2,s[i]
} .m3,s[i].tot,s[i].avg);
OUTPUT
Enter number of students: 2
Enter Student 1 details
Enter name: AAA
Enter Rollno: 101
Enter 3 subject marks: 90 89 98

Enter Student 2 details


Enter name: BBB
Enter Rollno: 102
Enter 3 subject marks: 78 90 89
STUDENTS MARK SHEET
Name Rollno Mark1 Mark2 Mark3 Total Avg
AAA 101 90 89 98 277 92.00
BBB 102 78 90 89 257 85.00

9
2. Program to Print employee details using Structure

#include <stdio.h>
struct Employee
{
char ename[20];
int id;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"ccc",1000,1000.50,{22,6,1990}};
void main()
{
printf("\nEmployee Name: %s",emp.ename);
printf("\nEmployee IDNo: %d",emp.id);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ: %d/%d/%d", emp. doj. date, emp.doj.month, emp.doj.year );
}

Output
Employee Name : ccc
Employee ID 1000
Employee Salary 50000
Employee DOJ : 22/6/1990

3. Program To print the given employee personal details using nested structure

#include<stdio.h>
#include<conio.h>
struct dob
{
int dd;
int mm;
int yy;
}dt;
struct address
{
char st[20];
char city[20];
}add; long int pin;
struct employee
{
int empid;
char name[20];
struct dob dt;
char pan[10];
long int phone;

10
struct address add;
char dept[10];
int exp;
}emp;
void main()
{
clrscr();
printf("Enter the Employee details:\n");
printf("\nEnter name and empid:");
scanf("%s%d",emp.name,&emp.empid);
printf("\nEnter Employee's date of birth:");
scanf("%d%d%d",&emp.dt.dd,&emp.dt.mm,&emp.dt.yy);
printf("\nEnter pan number and phone number:");
scanf("%s%ld",emp.pan,&emp.phone);
printf("Enter Employee's address details");
printf("\nEnter state, city and pin number:");
scanf("%s%s%ld",emp.add.st,emp.add.city,&emp.add.pin);
printf("\nEnter department and year of experience detail:");
scanf("%s%d",emp.dept,&emp.exp);
printf("\n");
printf("The Employee details are:\n");
printf("\nEmployee Name:\t%s",emp.name);printf("\nEmployee Id:\t%d",
emp.empid);
printf("\nEmployee DOB:\t%d\%d\%d",emp.dt.dd,emp.dt.mm,emp.dt.yy);
printf("\nEmployee Pan no:\t%s",emp.pan);
printf("\nEmployee Phone number:\t%ld",emp.phone);
printf("\nEmployee Address:\t%s\t%s\t%ld", emp.add.st, emp.add.city,
emp.add.pin);
printf("\nEmployee Department:\t%s",emp.dept);
printf("\nEmployee Year of Experience:\t%d",emp.exp);
} getch();

OUTPUT

Enter name and empid : AAA 101


Enter Employee's date of birth : 11 05 88
Enter pan number and phone number : 123456 9999999999
Enter Emplyee's address details
Enter state, city and pin number : TN CHENNAI 600030
Enter department and year of experience detail : CSE 08
The Employee details are:
Employee Name : AAA
Employee Id : 101
Employee DOB : 11 05 88
Employee Pan no : 123456
Employee Phone number : 999999999
Employee Address : TN CHENNAI 600030
Employee Department : CSE
Employee Year of Experience : 08

11
4. Program for Salary Slip Generation using structure
#include <stdio.h>
struct employee
{ char name[10];
int basic, da, hra, ta, others;
int pf,it;
int net_salary,gross_salary,deduction;
}e[10];
void main()
{
int i,n;
struct employee *ptr[10];
printf("enter the number of employee");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ptr[i]=&e[i];
printf("enter the name");
scanf("%s",ptr[i]->name);
printf("Enter Basic Salary (RS): ");
scanf("%d",&ptr[i]->basic);
ptr[i]->hra=(ptr[i]->basic*15)/100;
ptr[i]->ta=(ptr[i]->basic*20)/100;
ptr[i]->others=(ptr[i]->basic*10)/100;
//calculate DA 12% of Basic Salary
ptr[i]->da = (ptr[i]->basic*30)/100;
//calculate PF 14% of Basic salary
ptr[i]->pf = (ptr[i]->basic*2)/100;
//calculate IT, 15% of Basic salary
ptr[i]->it = (ptr[i]->basic*2)/100;
//calculate net salary
ptr[i]->gross_salary = ptr[i]->basic + ptr[i]->da + ptr[i]->hra + ptr[i]->ta +
ptr[i]->others;
ptr[i]->deduction=ptr[i]->pf+ptr[i]->it;
ptr[i]->net_salary=ptr[i]->gross_salary-ptr[i]-> deduction;
}
//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);
}
}
Output
enter the number of employee 2
enter the name aaa
Enter Basic Salary (RS): 100
enter the namebbb
Enter Basic Salary (RS): 200
Name is aaa Net Salary is:RS 171
Name is bbb Net Salary is:RS 342

12
5. Program for Student Database Program
#include<stdio.h>
#include<string.h>
struct student
. {
char name[20];
int roll_no, i;
int marks;
}a[10];
void main()
{
int i,n;
struct student *arr_student[10];
clrscr();
printf("enter the number of Student");
scanf("%d",&n);
printf("enter the Student Details one by one");
for(i=0;i<n;i++)
{
arr_student[i] = &a[i];
printf("\nEnter details of student" );
printf("Enter name: ");
scanf("%s", arr_student[i]->name);
printf("Enter roll no: ");
scanf("%d", &arr_student[i]->roll_no);
printf("Enter marks: ");
scanf("%d", &arr_student[i]->marks);
}
for(i=0;i<n;i++)
{
printf("\n");
printf("Name\tRoll no\tMarks\n");
printf("%s\t%d\t%d\n",arr_student[i]->name, arr_student[i]->roll_no,
arr_student[i]->marks);
}
getch();
}

Output:
enter the number of Student2
enter the Student Details one by one
Enter details of studentEnter name: xxx
Enter roll no: 45
Enter marks: 345
Enter details of studentEnter name: yyy
Enter roll no: 46
Enter marks: 509
Name Roll noMarks
xxx 45 345

Name Roll noMarks


yyy 46 509

13
6. Program for passing structure to function – Student Details
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
char grade[10];
int roll_no, i;
int marks1,marks2,marks3,percentage;
}s[10];
void internal(struct student s[],int);
void main()
{
int n,i;
clrscr();
printf("\n enter the number of student");
scanf("%d",&n);
printf("\n enter the Details one by one");
for(i=0;i<n;i++)
{
printf("\n Enter name: ");
scanf("%s", s[i].name);
printf("\n Enter roll no: ");
scanf("%d", &s[i].roll_no);
printf("\n Enter marks1: ");
scanf("%d", &s[i].marks1);
printf("\n Enter marks2: ");
scanf("%d", &s[i].marks2);
printf("\n Enter marks3: ");
scanf("%d", &s[i].marks3);
printf("\n Enter Attendance percentage:");
scanf("%d", &s[i].percentage);
}
internal(s,n);
getch();
}
void internal(struct student s[],int n)
{
int i;
float inter[10],atten[10];
for(i=0;i<n;i++)
{
if(s[i].percentage>95)atten[i]=5;
else
if(s[i].percentage>90)atten[i]=4;
else
if(s[i].percentage>85)atten[i]=3;
else
if(s[i].percentage>80)atten[i]=2;
else
if(s[i].percentage>75)atten[i]=1;
else

14
atten[i]=0;
inter[i]=(((s[i].marks1/100)*5)+((s[i].marks2/100)*5)+((s[i].marks3/100)*5)+
atten[i]);
printf("\n The student name is %s,\t internal mark is %f", s[i].name,
inter[i]);
}
}
OUTPUT
enter the number of student1
enter the Details one by one
Enter name: aaa
Enter roll no: 1
Enter marks1: 100
Enter marks2: 100
Enter marks3: 90
Enter Attendance percentage:100
The student name is aaa, internal mark is 15.000000

4.11 Dynamic Memory Allocation


The process of allocating memory during program execution is called dynamic memory
allocation.

Dynamic Memory Allocation Functions


C language offers 4 dynamic memory allocation functions. They are,
1. malloc( )
2. calloc( )
3. realloc( )
4. free( )
Function Syntax
malloc () malloc (number x sizeof(data type));
calloc () calloc (number, sizeof(data type));
realloc () realloc (pointer_name, number x sizeof(data type));
free () free (pointer_name);

malloc() function in C:
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initialize the memory allocated during execution. It carries garbage value.
malloc () function returns null pointer if it couldn‟t able to allocate requested amount of
memory.

Example Program for malloc() Function in C:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_alloc;
mem_alloc = malloc( 20 * sizeof(char));
if( mem_alloc== NULL )
{
printf("Couldn't able to allocate requested memory\n");

15
}
else
{
strcpy( mem_alloc,"Hello World");
}
printf("Dynamically allocated memory content : %s \n", mem_alloc );
free(mem_alloc);
}

OUTPUT
Dynamically allocated memory content: Hello World

calloc() function in C:
 calloc () function is also is used to allocate space in memory during the execution of the
program like malloc () function. But calloc () initializes the allocated memory to zero.
Example Program for calloc() function in C:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i, n;
int *a;
printf("Number of elements to be entered:");
scanf("%d",&n);
a = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ )
scanf("%d",&a[i]);
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ )
printf("%d ",a[i]);
free( a );
} return(0);
OUTPUT
Number of elements to be entered:5
Enter 5 numbers:
10 20 30 40 50
The numbers entered are: 10 20 30 40 50

realloc () function in C:
 realloc () function modifies the allocated memory size by malloc () and calloc () functions to
new size.
 If enough space doesn’t exist in memory of current block to extend, new block is
allocated for the fullsize of reallocation, then copies the existing data to new block and then
frees the old block.

free() function in C:
 free () function frees the allocated memory by malloc (), calloc (), realloc () functions and
returns thememory to the system.

16
Example Program for realloc() and free() functions in C:
#include<stdio.h>
void main()
{
char *p;
p=(char*)malloc(7);
strcpy(p," CHENNAI ");
printf("memory contains %s",p);
p=(char*)realloc(p,10);
strcpy(p,"VIJAYAWADA");
printf("\n memory now contains %s",p);
free(p);
}
OUTPUT
memory contains CHENNAI
memory now contains VIJAYAWADA

4.12 Self Referential Structure in C


A self referential data structure is a structure definition which includes at least one member that
is a pointer to the structure of its own kind. A chain of such structures can be expressed as
follows.
struct name
{
member 1;
member 2;
...
struct name *pointer;
};

Example :
struct node
{
int data;
struct node *next;
};

The following figure depicts the composition of such a node. The figure is a simplified
illustration of nodes that collectively form a chain of structures or linked list.

17
Example Program
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*start=NULL;
void main()
{
char ch;
struct node *current, *new_node;
do
{
new_node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to create : ");
scanf("%d",&new_node->data);
new_node->next=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{ current->next=new_node;
current=new_node;

}
printf("\nDo you want to create another: ");
ch=getche();
} while(ch!='n');
current=start;
printf("\n the linked list is");
do
{
printf("%d ->",current->data);
current=current->next;
}
while(current!=NULL);
printf(" NULL");
}
OUTPUT

Enter the data to create : 34


Do you want to create another : y
Enter the data to create : 23
Do you want to create another : y
Enter the data to create : 78
Do you want to create another : n
The linked list is 34->23->78->NULL

18
4.13 Linked List
Linked List i s a l i n e a r collection of data elements called nodes. These nodes are
randomly stored in the memory.
Node Structure: A node in a linked list typically consists of two
components: Data: It holds the actual value or data associated with
the node. Next Pointer: It stores the memory address of the next node in the sequence.
Head and Tail: The linked list is accessed through the head node, which points to the first
node in the list. The last node in the list points to NULL or nullptr, indicating the end of the
list. This node is known as the tail node.

Advantages of Linked List:


 Optimum Utilization of Memory : The list is not required to be contiguously present in the
memory. The node can reside anywhere inthe memory and linked together to make a list.
 Dynamic Data structure: The size of memory can be allocated or de-allocated at run
time based on the operation insertion or deletion.
 Ease of Insertion/Deletion: The insertion and deletion of elements are simpler than arrays
since no elements need to be shifted after insertion and deletion, Just the address needed to be
updated.
 Efficient Memory Utilization: Linked List is a dynamic data structure the size
increases or decreases as per the requirement so this avoids the wastage of memory.
 Implementation / Applications: Various advanced data structures can be implemented using a
linked list like a stack, queue, graph, hash maps, etc. It is also used in Memory management

Disadvantages of Linked Lists


Direst Access not possible : Unlike arrays, linked lists do not allow direct access to elements
byindex. Traversal is required to reach a specific node.
Extra Memory: Linked lists require additional memory for storing the pointers, compared to
arrays.

Types of linked lists: There are mainly three types of linked lists:
1. Single-linked list
2. Double linked list
3. Circular linked list

Single linked list


Single linked list can be defined as the collection of ordered set of elements. The number of
elements may vary according to need of the program.
A node in the single linked list consists of two parts: data part and link part.
Data part of the node stores actual information that is to be represented by the node while the
link part of the node stores the address of its immediate successor.
Single linked list can be traversed only in one direction.

19
Node Creation
struct node
{
int data;
struct node *next;
};
struct node *head, *ptr;
ptr = (struct node *)malloc(sizeof(struct node *));

4.14 Operations on Single linked list :


The following operations are performed on a Single Linked List
a. Insertion: The insertion operation can be performed in three ways. They are as follows:
 Inserting At the Beginning of the list
 Inserting At Specific location in the list
 Inserting At End of the list
b. Deletion: The deletion operation can be performed in three ways. They are as follows…
 Deleting from the Beginning of the list
 Deleting a Specific Node
 Deleting from the End of the list
c. Search: It is a process of searching a specific node in the list.
d. Display: This process displays the elements of a Single-linked list.

a. Insertion in Linked List


Inserting a new node in a Linked List can be done at the following positions:
At the front of the linked list
After a given node.
At the end of the linked list.

1. To insert a node at the start/beginning/front of a Linked List, we need to:


Make the first node of Linked List linked to the new node
Remove the head from the original first node of Linked List
Make the new node as the Head of the Linked List.

2. To insert a node after a given node in a Linked List, we need to:


Make the element to be inserted as a new node
Change the next pointer of given node to the new node
Now shift the original next pointer of given node to the next pointer of new node

20
3. To insert a node at the end of a Linked List, we need to:
Go to the last node of the Linked List
Change the next pointer of last node from NULL to the new node
Make the next pointer of new node as NULL to show the end of Linked List

b. Delete from a Linked List:-


We can delete an element in a Linked list from:
Beginning
End
Middle
1. Deleting a node from the beginning:
 Set the head node to the next node in the list.
 Free the original head node.

2. Deleting a node from the middle:


 Traverse the linked list until you reach the node that you want to delete.
 Set the node before the one you want to delete to point to the node after the one you want
to delete.
 Free the node you wanted to delete.

3. Deleting a node from the end:


 Traverse the linked list until you reach the second-to-last node in the list.
 Set the next pointer of the second-to-last node to None.

We have to properly deallocate any memory used by the deleted node to avoid memory leaks.

21
//Program for insertion, deletion , display operations on linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;

void beginsert();
void begin_delete();
void display();
void main()
{
beginsert();
beginsert();
beginsert();
display();
begin_delete();
display();
}
void beginsert()
{

struct node *ptr;


int item;
ptr = (struct node *) malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted");
}
}

void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{

22
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}

void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("\n printing values in list \n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}

Output :
Enter value
10
Node inserted
Enter value
20
Node inserted
Enter value
30
Node inserted
printing values in list

30
20
10
Node deleted from the begining ...

printing values in list


20
10

23
// Example Program2 for all operations on linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;

void beginsert();
void lastinsert();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();

void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n\n*********Main Menu*********\n");
printf("\n Choose one option from the following list ...\n");
printf("\n===============================\n");
printf("\n 1.Insert in beginning \n
2. Insert at last \n
3. Insert at any random location \n
4.Delete from Beginning \n
5.Delete from last \n
6.Delete node after specified location \n
7.Search for an element \n
8.Show \n
9.Exit \n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
randominsert();
break;
case 4:
begin_delete();
break;

24
case 5:
last_delete();
break;
case 6:
random_delete();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}

void beginsert()
{

struct node *ptr;


int item;
ptr = (struct node *) malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{ printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted");
}
}

void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else

25
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr;
} printf("\nNode inserted");
else
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted");
}
}
}

void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{ printf("\n Enter element value");
scanf("%d",&item);
ptr->data = item;
printf("\n Enter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}
}
ptr ->next = temp ->next;
temp ->next = ptr;

26
printf("\nNode inserted");
}
}

void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{ ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}

void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
} printf("\nOnly node of the list deleted ...\n");
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n");
}
}

void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion

27
\n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}

void search()
{
struct node *ptr;
int item, i=0, flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{ printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d", i+1);
flag=0;
}
else
{ flag=1;

}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not found\n");
}
}
}
void display()

28
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{ printf("\n printing values \n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}

Output:

*********Main Menu********* *********Main Menu*********


Choose one option from the following list Choose one option from the following list
============================= =============================
1. Insert in beginning 1. Insert in beginning
2. Insert at last 2. Insert at last
3. Insert at any random location 3. Insert at any random location
4. Delete from Beginning 4. Delete from Beginning
5. Delete from last 5. Delete from last
6. Delete node after specified location 6. Delete node after specified location
7. Search for an element 7. Search for an element
8. Show 8. Show
9. Exit 9. Exit
Enter your choice? Enter your
1 Enter value1 choice?2 Enter
Node inserted value?2
Node inserted
*********Main Menu********* *********Main Menu*********
Choose one option from the following list Choose one option from the following list
============================= =============================
1. Insert in beginning 1. Insert in beginning
2. Insert at last 2. Insert at last
3. Insert at any random location 3. Insert at any random location
4. Delete from Beginning 4. Delete from Beginning
5. Delete from last 5. Delete from last
6. Delete node after specified location 6. Delete node after specified location
7. Search for an element 7. Search for an element
8. Show 8. Show
9. Exit 9. Exit
Enter your Enter your
choice?3 Enter choice?8 printing
element value1 values . . . 1
Enter the location after which you want to 2
insert 1Node inserted 1

29
*********Main Menu********* *********Main Menu*********
Choose one option from the following list Choose one option from the following list
============================= =============================
1. Insert in beginning 1. Insert in beginning
2. Insert at last 2. Insert at last
3. Insert at any random location 3. Insert at any random location
4. Delete from Beginning 4. Delete from Beginning
5. Delete from last 5. Delete from last
6. Delete node after specified location 6. Delete node after specified location
7. Search for an element 7. Search for an element
8. Show 8. Show
9. Exit 9. Exit

Enter your choice?2 Enter your choice?1


Enter Enter
value?123 value1234
Node Node
inserted inserted
*********Main Menu********* *********Main Menu*********
Choose one option from the following list Choose one option from the following list
============================= =============================
1. Insert in beginning 1. Insert in beginning
2. Insert at last 2. Insert at last
3. Insert at any random location 3. Insert at any random location
4. Delete from Beginning 4. Delete from Beginning
5. Delete from last 5. Delete from last
6. Delete node after specified location 6. Delete node after specified location
7. Search for an element 7. Search for an element
8. Show 8. Show
9. Exit 9. Exit

Enter your choice?4 Enter your choice?5


Node deleted from the beginning Deleted Node from
the last
*********Main Menu********* *********Main Menu*********
Choose one option from the following list Choose one option from the following list
============================= =============================
1. Insert in beginning 1. Insert in beginning
2. Insert at last 2. Insert at last
3. Insert at any random location 3. Insert at any random location
4. Delete from Beginning 4. Delete from Beginning
5. Delete from last 5. Delete from last
6. Delete node after specified location 6. Delete node after specified location
7. Search for an element 7. Search for an element
8. Show 8. Show
9. Exit 9. Exit
Enter your choice?6 Enter your
Enter the location of the node after which you choice?8
want to perform deletion1 printing values
Deleted node 2 1
1

30
*********Main Menu********* *********Main Menu*********
Choose one option from the following list Choose one option from the following list
============================= =============================
1. Insert in beginning 1. Insert in beginning
2. Insert at last 2. Insert at last
3. Insert at any random location 3. Insert at any random location
4. Delete from Beginning 4. Delete from Beginning
5. Delete from last 5. Delete from last
6. Delete node after specified location 6. Delete node after specified location
7. Search for an element 7. Search for an element
8. Show 8. Show
9. Exit 9. Exit
Enter your choice?7
Enter item which you want to Enter your choice?9
search?1 item found at location
1
item found at location 2

31
4.15 typedef:
typedef is used to assign alternative names for existing data types. It is used for syntactic
convenience of the user only.
Syntax:
typedef <Existing_data_type> <user defined datatype>;
Example : typedef int number
It is mostly used with user defined datatypes such as structures as the name of the data type
becomes slightly complicated to use in the programs
Example :
typedef struct student
{
char name[50];
int roll;
float marks;
}student_list;
Here stu represents the structure definition associated with it. So it can be used to declare the
variable for this structure as in below statement
Student_list s1,s2;

Example Program
#include <stdio.h>
typedef struct student
{
char name[50];
int roll;
float marks;
}stu;
void main()
{
stu s;
printf("Enter information of students:\n");
printf("\nEnter roll number:");
scanf("%d",&s.roll);
printf("Enter name: "); Output :
scanf("%s",s.name); Enter information of students:
printf("Enter marks: ");
scanf("%f",&s.marks); Enter roll number:1
printf("\n"); Enter name: aaa
Enter marks: 490
printf("Displaying Information:\n");
Displaying Information:
// displaying information
printf("\nRoll number: %d\n",s.roll); Roll number: 1
printf("Name: "); Name: aaa
puts(s.name); Marks: 490.0
printf("Marks: %.1f",s.marks);
printf("\n");
}

32
4.16 Union:
Union is a collection of different types of variables under single name.
Union and structure in C are same in concepts, except allocating memory for their members.
Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members
We can access only one member of union at a time. We can’t access all member values at
the sametime in union. But, structure can access all member values at the same time.
Many union variables can be created in a program and memory will be allocated for each
unionvariable separately.
Below table will help you how to form a C union, declare a union, initializing and accessing
themembers of the union.

33
Example Program For Union:
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
void main()
{
union student record1;
union student record2;
clrscr();
/* assigning values to record1 union variable */
strcpy(record1.name, "AAAA");
strcpy(record1.subject, "Maths");
record1.percentage = 97.50;
printf("Union record1 values example\n");
printf("Name : %s \n", record1.name);
printf("Subject : %s \n", record1.subject);
printf("Percentage : %f \n\n", record1.percentage);
/* assigning values to record2 union variable */
printf("Union record2 values example\n");
strcpy(record2.name, "BBBB");
printf("Name : %s \n", record2.name);
strcpy(record2.subject, "Programming in C");
printf("Subject : %s \n", record2.subject);
record2.percentage = 99.50;
printf("Percentage : %f \n", record2.percentage);
getch();
}

OUTPUT:
Union record1 values example
Name :
Subject :
Percentage : 97.500000

Union record2 values example


Name : BBBB
Subject : Programming in C
Percentage : 99.500000

Explanation : The values of record1 is not fully printed because Union allocates one common
storage space for all its members. Hence the percentage which is stored lastly gets printed. In case
of record2, the display of values is done immediately after assigning the values. So all the values are
displayed

34
4.17 Comparison (or Difference) between Structure and Union:

S.No Structure Union


1 struct keyword is used in Structure union keyword is used in union declaration
declaration
2 Structure allocates storage space for all Union allocates one common storage space for
its members separately all its members

3 We can access more than one member of We can access only one member of union at a
stucture at a time time
4 The size of the structure is equal to the The size is equal to the size of the largest
sum of the size of members member
structure
5 Altering the value of any member willnot Altering the value of any member will affect
affect other members of the other members of the structure
structure
6 Syntax: Syntax:
struct <tag name> union <tag-name>
{datatype member1; {datatype member1;
datatype member2; datatype member2;
……. …….
…… ……
datatype member n ; datatype member n ;
}; };
4.18 Storage classes and Visibility

Refer Unit 1 – Page no. 6


4.19 Comparison between malloc and calloc:

S.No malloc( ) calloc( )

malloc( ) is a function that creates one calloc( ) is a function that assigns a specified
1. block of memory of a fixed size. number of blocks of memory

2. malloc( ) only takes one argument calloc( ) takes two arguments.

3. malloc( ) is faster than calloc. calloc( ) is slower than malloc( )

4. malloc( ) has high time efficiency calloc( ) has low time efficiency

Syntax : malloc (number x


5. sizeof(datatype)); Syntax : calloc (number, sizeof(datatype));

malloc( ) does not initialize the


6 memory to zero calloc ( ) initializes the memory to zero

35
UNIT – IV - PART - A
1. What is structure? Write the syntax for structure.
2. What is meant by structure definition?
3. Write the various operations structure.
4. How the members of structure object is accessed?
5. Write the use of size operator on structure.
6. What is a nested structure?
7. How typedef is used in structure?
8. Interpret the term Union in C.
9. What is mean by Self referential structures?
10. What is the need for typedef?
11. In language C can we allocate memory dynamically? How?
12. Point out the meaning of Dynamic memory allocation.
13. Mention any two application linked list.
14. Generalize the operators used in access the structure members.
15. State the meaning of the root word struct.
16. Show the difference between Structures from Array.
17. Show a structure called ID_Card to hold the details of a student.
18. Summarize the different types of memory allocation functions.
19. Discriminate between malloc and calloc.
20. If we have structure B nested inside structure A, when do we declare structure B?
21. How to create a node in singly liked list?
22. Compare and contrast Structure with Union
23. Write the syntax for pointers to structure.
What is the output of the following code fragment?
struct point
{
int x, y;
};
24. struct point origin, *pp;
main ()
{
pp = & origin;
printf (" origin is (%d%d)\n", (*pp).x,pp →y);
}
25. Discover the meaning of Array of structure.

36
PART – B
1. Discuss about various storage classes and its visibility
2. Explain about the structures and its operations.
3. Why is singly linked list called as self-referential structure? Explain.
4. Demonstrate about pointers to structures, array of structures and nested structures.
5. Write a C program using structures to prepare the students mark statement.
6. Write a C program using structures to prepare the employee pay roll of a company.
7. Write a C program to read the details of book name, author name and price of 200
books in a library and display the total cost of the books.
What is a structure? Express a structure with data members of various types and
8. declare two structure variables. Write a program to read data into these and printthe same.

9. Justify the need for structured data type.


10. What is dynamic memory allocation? Explain various C functions that are used for
the same with examples.
11. What is the need for structure data type? Does structure bring additional overhead
to a program? Justify.
12. Write short note on structure declaration.
13. How to Accessing the structure member through pointer using dynamic memory
allocation.
Define a structure called student that would contain name, regno and marks of five subjects
14. and percentage. Write a C program to read the details of name, regno and marks of five
subjects for 30 students and calculate the percentage and display the
name, regno, marks of 30 subjects and percentage of each student
15. Explain with an example the self-referential structure.
16. Explain singly linked list and write C Program to Implement Singly Linked List using
Dynamic Memory Allocation.
Discuss about the following
17.  Singly linked list and operation.
 Advantage and disadvantage of singly linked list.
18. Illustrate a C program to store the employee information using structure and search
a particular employee details.
19. Write a C program for accessing structure member through pointer using dynamic
memory allocation.
20. Write a C program using structures to prepare the students mark statement. The
number of records is created based on the user input.

37

You might also like