CH 11 Data Structures (Without Pointer)
CH 11 Data Structures (Without Pointer)
11.1 Introduction
A data structure is a set of rules for storing data in a systematic way. One data structure called
array which is a collection of values of the same data types. Other data structures such as
queues, stacks and linked lists will be discussed in this chapter.
11.2 Structure
Structure is the collection of variables of different types under a single name for better
handling. For example: You want to store the information about student about his/her name,
class, class number and sex. You can create these information separately but, better approach
will be collection of these information under single name because all these information are
related to a student.
Syntax of structure:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
struct person
{
char name[50];
int ID_no;
float salary;
};
There are two types of operators used for accessing members of a structure.
Ø Member operator(.)
Ø Structure pointer operator(->) (will be discussed in structure and pointers chapter)
Suppose, we want to access salary for variable p2. Then, it can be accessed as:
p2.salary
Ch 11 Data structures 3
Example 11.1
Write a C program to add two distances entered by user. Measurement of distance should
be in inch and feet.(Note: 12 inches = 1 foot)
#include <stdio.h>
struct Distance{
int feet;
float inch;
}d1,d2,sum;
int main(){
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet); /* input of feet for structure variable d1 */
printf("Enter inch: ");
scanf("%f",&d1.inch); /* input of inch for structure variable d1 */
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d",&d2.feet); /* input of feet for structure variable d2 */
printf("Enter inch: ");
scanf("%f",&d2.inch); /* input of inch for structure variable d2 */
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
if (sum.inch>12){ //If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch=sum.inch - 12;
}
printf("Sum of distances=%d\'-%.1f\"", sum.feet, sum.inch);
/* printing sum of distance d1 and d2 */
return 0;
}
Sample output
Ch 11 Data structures 4
Programmer generally use typedef while using structure in C language. For example:
typedef struct complex{
int imag;
float real;
}comp;
Inside main:
comp c1,c2;
Here, typedef keyword is used in creating a type comp(which is of type as struct complex).
Then, two structure variables c1 and c2 are created by this comp type.
Write a C program to create a structure student, containing name and roll. Ask user the name
and roll of a student in main function. Pass this structure to a function and display the
information in that function.
Example 11.4
#include <stdio.h>
struct student{
char name[50];
int roll;
};
void Display(struct student stu);
/* function prototype should be below to the structure declaration otherwise compiler
shows error */
int main(){
struct student s1;
printf("Enter student's name: ");
scanf("%s",&s1.name);
printf("Enter roll number:");
scanf("%d",&s1.roll);
Display(s1); // passing structure variable s1 as argument
return 0;
Ch 11 Data structures 5
}
void Display(struct student stu){
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Sample output
The address location of structure variable is passed to function while passing it by reference.
If structure is passed by reference, change made in structure variable in function definition
reflects in original structure variable in the calling function.
Write a C program to add two distances(feet-inch system) entered by user. To solve this
program, make a structure. Pass two structure variable (containing distance in feet and inch)
to add function by reference and display the result in main function without returning it.
Example 11.5
#include <stdio.h>
struct distance{
int feet;
float inch;
};
void Add(struct distance d1,struct distance d2, struct distance *d3);
int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d",&dist1.feet);
printf("Enter inch: ");
scanf("%f",&dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d",&dist2.feet);
printf("Enter inch: ");
scanf("%f",&dist2.inch);
Ch 11 Data structures 6
/*passing structure variables dist1 and dist2 by value whereas passing structure variable
dist3 by reference */
printf("\nSum of distances = %d\'-%.1f\"",dist3.feet, dist3.inch);
return 0;
}
void Add(struct distance d1,struct distance d2, struct distance *d3)
{
/* Adding distances d1 and d2 and storing it in d3 */
d3->feet=d1.feet+d2.feet;
d3->inch=d1.inch+d2.inch;
if (d3->inch>=12) { /* if inch is greater or equal to 12, converting it to feet. */
d3->inch-=12;
++d3->feet;
}
}
Sample output
In this program, structure variables dist1 and dist2 are passed by value (because value of dist1
and dist2 does not need to be displayed in main function) and dist3 is passed by reference, i.e,
address of dist3 (&dist3) is passed as an argument. Thus, the structure pointer variable d3
points to the address of dist3. If any change is made in d3 variable, effect of it is seed in dist3
variable in main function.
Ch 11 Data structures 7
11.3 Queues
Queue is also an abstract data type or a linear data structure, in which the first element is
inserted from one end called REAR(also called tail), and the deletion of existing element
takes place from the other end called as FRONT(also called head). This makes queue as First-
In-First-Out (FIFO) data structure, which means that element inserted first will also be
removed first.
The process to add an element into queue is called Enqueue and the process of removal of
an element from queue is called Dequeue.
Applications of Queue
Queue, as the name suggests is used whenever we need to have any group of objects in an
order in which the first one coming in also gets out first while the others wait for their turn,
like in the following scenarios :
Ø Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
Ø In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
Ø Handling of interrupts in real-time systems. The interrupts are handled in the same order
as they arrive, First come first served.
Implementation of queue
The easiest way of implementing a queue is by using an Array. Initially the head(FRONT) and
the tail(REAR) of the queue points at the first index of the array (starting the index of array
from 0). As we add elements to the queue, the tail keeps on moving ahead, always pointing
to the position where the next element will be inserted, while the head remains at the first
index.
The terminology for the insert operation on queues is called: Insert, Enter or Enqueue;
whereas, the remove operation is called: Delete, Remove or Dequeue.
The advantage of using a queue is that multiple requests can be kept in a queue so they can
share a single resource.
Example 11.6
#include<stdio.h>
#include<conio.h>
#define MAX 10
void insert(int);
int del();
int queue[MAX], rear=0, front=0;
void display();
int main()
{
char ch , a='y';
int choice, token;
printf("1.Insert");
printf("\n2.Delete");
Ch 11 Data structures 9
printf("\n3.show or display");
do
{
printf("\nEnter your choice for the operation: ");
scanf("%d",&choice);
switch(choice)
{
case 1: insert(token);
display();
break;
case 2:
token=del();
printf("\nThe token deleted is %d",token);
display();
break;
case 3:
display();
break;
default:
printf("Wrong choice");
break;
}
printf("\nDo you want to continue(y/n):");
ch=getch();
}
while(ch=='y'||ch=='Y');
getch();
}
void display()
{
int i;
printf("\nThe queue elements are:");
for(i=front;i<rear;i++)
{
printf("%d ",queue[i]);
}
Ch 11 Data structures 10
}
void insert(int token)
{
char a;
if(rear==MAX)
{
printf("\nQueue full");
return;
}
do
{
printf("\nEnter the token to be inserted:");
scanf("%d",&token);
queue[rear]=token;
rear=rear+1;
printf("do you want to continue insertion Y/N");
a=getch();
}
while(a=='y');
}
int del()
{
int t;
if(front==rear)
{
printf("\nQueue empty");
return 0;
}
t=queue[front];
front=front+1;
return t;
}
Ch 11 Data structures 11
11.4 Stacks
A stack is a special kind of data structures in which data is added and deleted at only one
end of a list called the top of the stack. For example, when a
stack of books are placed on a desk, people can only take the
books from or put books on the top of the stack. In this way,
the last item added onto a stack is always the first one to be
removed. Items are added and removed in a Last-In-First-Out
(LIFO) order.
The operation to add an item to a stack is called "push" and the operation to remove an
item from a stack is called "pop".
Example 11.7
#include <stdio.h>
#define MAXSIZE 5
/* Function declaration/Prototype*/
int main ()
{
int choice;
int option = 1;
s.top = -1;
switch (choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: return 0;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}
Queue Stack
Usage Common Few
Structure Simple linear data structure; Simple linear data structure;
grows in one direction grows in one direction
(lengthy queue) (pushdown stack)
Size Length of queue depth of a stack
Type FIFO LIFO
Example of usage Print jobs in printing queue Calling procedures and
functions
Ø To insert or remove an item from an array involves shifting of contents from one element
to another element. If the array size is large, an operation of data insertion or deletion
on the array is very time-consuming due to the movements of array elements.
Ø Besides, the size of the array must be declared first before program execution, making
the program not flexible. If a large array is needed when the program is running, there is
no way to satisfy this request.
Ø In order to overcome these problems, dynamic data structures are needed and one of
these is the linked list.
Ch 11 Data structures 15
A linked list is a collection of data in which each element contains the location of the next
element; that is, each element contains two parts : data and next (or link). The data part holds
the useful information, the data to be processed.
The next (or link) is used to chain the data together. It contains a pointer that identifies the
next node in the list. The variable of next storing the position of the next record.
In a linked list, each record is called a node, which consists of two elements, the data and the
variable storing the position of the next record. The following diagrams show the operations
of linked list.
The advantage of such a structure is that elements may be inserted and deleted by making
use of pointers rather than by physical movement of the data.
A list of empty elements, called free list, is maintained. Additions to the linked lists are made
by removing the first element from the free list, and inserting it in, or appending it to, the
linked list. Similarly, an element deleted from a linked list may be added back to the front of
the free list. This process is called garbage collection.
Ch 11 Data structures 16