0% found this document useful (0 votes)
49 views

CH 11 Data Structures (Without Pointer)

The document discusses data structures in C programming. It introduces structures as a way to group related data types under a single name. Structures are defined using the struct keyword and members are accessed using the dot operator. Structures can be passed to functions by value or by reference. Queues are described as a first-in, first-out data structure where elements are added to the rear and removed from the front. An array implementation of a queue is presented with functions to insert and delete elements. An example program demonstrates inserting and deleting tokens from a queue.

Uploaded by

sagiri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

CH 11 Data Structures (Without Pointer)

The document discusses data structures in C programming. It introduces structures as a way to group related data types under a single name. Structures are defined using the struct keyword and members are accessed using the dot operator. Structures can be passed to functions by value or by reference. Queues are described as a first-in, first-out data structure where elements are added to the rear and removed from the front. An array implementation of a queue is presented with functions to insert and delete elements. An example program demonstrates inserting and deleting tokens from a queue.

Uploaded by

sagiri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Ch 11 Data structures 1

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.

11.2.1 Structure Definition in C

Keyword struct is used for creating a structure.

Syntax of structure:
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};

We can create the structure for a person as mentioned above as:


struct person
{
char name[50];
int ID_no;
float salary;
};
This declaration above creates the derived data type struct person.
Ch 11 Data structures 2

11.2.2 Structure variable declaration

struct person
{
char name[50];
int ID_no;
float salary;
};

Inside main function:


struct person p1, p2, p[20];

Another way of creating structure variable is:


struct person
{
char name[50];
int ID_no;
float salary;
}p1 ,p2 ,p[20];
In both cases, 2 variables p1, p2 and array p having 20 elements of type struct person are
created.

11.2.3 Accessing members of a structure

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)

Any member of a structure can be accessed as: structure_variable_name.member_name

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

11.2.4 Keyword typedef while using structure

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.

11.2.5 Passing structure by value

A structure variable can be passed to the function as an argument as normal variable. If


structure is passed by value, change made in structure variable in function definition does not
reflect in original structure variable in calling function.

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

11.2.6 Passing structure by reference

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

Add(dist1, dist2, &dist3);

/*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.

It is a First-In, First-Out (FIFO) process.


Ch 11 Data structures 8

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.

Basic operations of stack

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

struct stack /* Structure definition for stack */


{
int stk[MAXSIZE];
int top;
};

typedef struct stack STACK;


STACK s;

/* Function declaration/Prototype*/

void push (void);


int pop(void);
void display (void);
Ch 11 Data structures 12

int main ()
{
int choice;
int option = 1;

s.top = -1;

printf ("STACK OPERATION\n");


while (option)
{
printf ("------------------------------------------\n");
printf (" 1 --> PUSH \n");
printf (" 2 --> POP \n");
printf (" 3 --> DISPLAY \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");

printf ("Enter your choice\n");


scanf ("%d", &choice);

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

/*Function to add an element to the stack*/


void push ()
{
Ch 11 Data structures 13

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

/*Function to delete an element from the stack*/


int pop ()
{
int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);
}
else
{
num = s.stk[s.top];
printf ("poped element is = %d\n", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);
}

/*Function to display the status of the stack*/


void display ()
{
int i;
if (s.top == -1)
{
Ch 11 Data structures 14

printf ("Stack is empty\n");


return;
}
else
{
printf ("\nThe status of the stack is\n");
for (i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}

11.5 Comparison between queue and stack

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

11.6 Linked Lists

Ø 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.

Inserting an item to a linked list

Removing an item from a 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

You are advised to use linked lists when


Ø The size of the record is large;
Ø The size of the list is not known in advance;
Ø There is plenty of insertion, deletion, and arrangement of the list.

11.7 Comparison between array and linked list

Array Linked list


Size Static : fixed-size Dynamic : variable-size
Access Allows direct read/write access to Allows access by navigating from the first
method any array element element to the target element
Insert / Poorly performed Well performed
Delete
Search Sequential search is used for Can only use sequential search.
speed searching in unordered array. Sequential search is used for searching
Speed is in the order of N. from the first element to the target
element. Speed is in the order of N.
Ease of Easy and simple; available in Difficult; not available in some
use most programming languages. programming languages.
Use of Efficient. If you declare a large Efficient. Every element is used.
storage size array, but most of the
elements in the array are empty
or not used, it causes high
wastage.

You might also like