Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
In the modern world, Data and its information is an essential part, and various
implementations are being made to store in different ways. Data are just a collection of facts
and figures, or you can say data are values or a set of values that are in a particular format. A
data item refers to a single set of values. Data items are then further categorized into sub-items
which are the group of items which are not being called a plain elementary form of items. Let
us take an example where the name of the student may be divided into three sub-items
namely: first name, middle name and last name. But the ID that is assigned to a student would
normally be considered as a single item.
Firstly, it must be loaded enough in structure to reflect the actual relationships of the
data with the real world object.
Secondly, the formation should be simple enough so that anyone can efficiently process
the data each time it is necessary.
The first way is to provide the linear relationships among all the elements represented
using linear memory location. These linear structures are termed as arrays.
The second technique is to provide a linear relationship among all the elements
represented by using the concept of pointers or links. These linear structures are termed
as linked lists.
Arrays
Queues
Stacks
Linked lists
Graphs
table of contents
Tree: In this case, data often contain a hierarchical relationship among various elements. The
data structure that reflects this relationship is termed as a rooted tree graph or a tree.
Graph: In this case, data sometimes hold a relationship between the pairs of elements which is
not necessarily following the hierarchical structure. Such a data structure is termed as a Graph.
In most of the cases, the vast amount of information which is to be developed in some
sense signifies a concept of a part of reality. The information that is accessible to the computer
consists of a specific set of data about the real problem that is set that and is considered
applicable to the problem at hand. The data signifies an abstraction of reality in the sense which
certain properties and distinctiveness of the real objects get ignored as they are peripheral and
inappropriate to the particular problem. A concept of abstraction is thereby also an overview of
facts.
In this chapter, you will learn about the fundamental elements of the data structure.
Each operator and function expects some arguments of a fixed type which is
represented by assigning a data type to those specific sets of arguments and yields a
result of a fixed type. If an operator declares arguments of several types such as the '+'
will be used for addition of both integers and real numbers, then the type of the answer
can be determined from specific language rules.
Built-in data type: These types of data types are predefined and has a fixed set of rules for
declaration. In other words, these data types when belonging to a particular programming
language has built-in support, and hence they are also called as built-in data types. Examples of
such data types are:
1. Integer type
2. Boolean type
3. Character type
4. Floating type
Derived Data type: These data types can be implemented independently within a
language. These data types are built by combining both primary and built-in data types
and then associating operations on them. Examples of such data types are:
5. Array
6. Stack
7. Queue
8. List
You might be familiar with these basic data types if you have read either C or C++. For
dealing with the various concepts of data structures, you can use any programming language.
But it is recommended to use either C or C++ for better implementation purpose.
Traversing
Searching
Insertion
Deletion
Sorting
Merging
Following are the essential terminologies used for understanding the concepts of Arrays:
Index: each memory location of an element in an array is denoted by a numerical index which is
used for identifying the element
So if the total run of each player is getting stored in separate variables, using arrays you
can bring them all into one array having single name like: plrscore[11];
0
and so on....
int votes[4];
Basic Operations
There is some specific operation that can be performed or those that are supported by
the array. These are:
What is stack?
A stack is a linear data structure in which all the insertion and deletion of data or you
can say its values are done at one end only, rather than in the middle. Stacks can be
implemented by using arrays of type linear.
The stack is mostly used in converting and evaluating expressions in Polish notations, i.e.:
Infix
Prefix
Postfix
In case of arrays and linked lists, these two allows programmers to insert and delete
elements from any place within the list, i.e., from the beginning or the end or even from the
middle also. But in computer programming and development, there may arise some situations
where insertion and deletion require only at one end wither at the beginning or end of the list.
The stack is a linear data structure, and all the insertion and deletion of its values are done in
the same end which is called the top of the stack. Let us suppose take the real-life example of a
stack of plates or a pile of books etc. As the item in this form of data structure can be removed
or added from the top only which means the last item to be added to the stack is the first item
to be removed. So you can say that the stack follows the Last In First Out (LIFO) structure.
If the stack is not full, add or insert a new node at the top of the stack. This operation is
termed as Push Operation
If the stack is not empty, then retrieve the node at its top
If the stack is not empty, the delete the node at its top. This operation is called as Pop
operation
#include<stdio.h>
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int main()
{
charexp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the valid postfix expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}
Concepts of Queue in Data Structure
The queue is a linear data structure used to represent a linear list. It allows insertion of
an element to be done at one end and deletion of an element to be performed at the other
end.
In this chapter, you will be given an introduction to the basic concepts of queues along
with the various types of queues which will be discussed simulating the real world situation.
What is a Queue?
A queue is a linear list of elements in which deletion of an element can take place only
at one end called the front and insertion can take place on the other end which is termed as the
rear. The term front and rear are frequently used while describing queues in a linked list. In this
chapter, you will deal with the queue as arrays.
In the concept of a queue, the first element to be inserted in the queue will be the first
element to be deleted or removed from the list. So Queue is said to follow the FIFO (First In
First Out) structure. A real-life scenario in the form of example for queue will be the queue of
people waiting to accomplish a particular task where the first person in the queue is the first
person to be served first.
Other examples can also be noted within a computer system where the queue of tasks
arranged in the list to perform for the line printer, for accessing the disk storage, or even in the
time-sharing system for the use of CPU. So basically queue is used within a single program
where there are multiple programs kept in the queue or one task may create other tasks which
must have to be executed in turn by keeping them in the queue.
First, there should be a particular way in which components are related to each other
Second, a statement for the operation that can be performed on elements of abstract
data type must have to be specified
Thus for defining a Queue as an abstract data type, these are the following criteria:
Insert a new element after the last element in a queue, if the queue is not full
#include<stdio.h>
#include<conio.h>
#define SIZE 5
void insert(int);
void Delete();
void display();
int a[5],r=-1,f=-1;
void main()
{
intitem,choice;
clrscr();
for(;;)
{
printf("\n\n***MENU***\n\n");
printf("1.Insert\n2.Delete\n3.Display\n4.Exit\n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("enter the item to be inserted\n");
scanf("%d",&item);
insert(item);
break;
case 2:Delete();
break;
case 3:display();
break;
case 4:exit(0);
break;
}
}
}
void insert(int item)
{
if(r==SIZE-1)
printf("queue overflow\n");
else
{
r=r+1;
a[r]=item;
printf("Insertion successful\n");
f=0;
}
}
void Delete()
{
if(f==-1 || f>r)
printf("queue is empty");
else
{
printf("Deleted item is %d",a[f]);
f=f+1;
}
}
void display()
{
if(f==-1 || f>r)
printf("queue is empty");
else
{
int i;
printf("elements in queue are:\n");
for(i=f;i<=r;i++)
printf("%d\n",a[i]);
}
getch();
}
Searching Techniques
This chapter explores various searching techniques. The process of identifying or finding
a particular record is called Searching. You often spend time in searching for any desired item. If
the data is kept properly in sorted order, then searching becomes very easy and efficient. In this
chapter, you will get to know the basic concepts of searching that are used in the data structure
and case of programming also.
What is searching?
Searching is an operation or a technique that helps finds the place of a given element or
value in the list. Any search is said to be successful or unsuccessful depending upon whether
the element that is being searched is found or not. Some of the standard searching technique
that is being followed in the data structure is listed below:
Binary Search
As against this, searching in case of unsorted list also begins from the 0th element and
continues until the element or the end of the list is reached.
The list given above is the list of elements in an unsorted array. The array contains ten
elements. Suppose the element to be searched is '46', so 46 is compared with all the elements
starting from the 0th element, and the searching process ends where 46 is found, or the list
ends.
The performance of the linear search can be measured by counting the comparisons done to find out an
element. The number of comparison is 0(n).
It is a simple algorithm that searches for a specific item inside a list. It operates looping
on each element O(n) unless and until a match occurs or the end of the array is reached.
algorithm Seqnl_Search(list, item)
Pre: list != ;
index <- fi
while index < list.Cnt and list[index] != item //cnt: counter variable
end while
return index
end if
return: 1
end Seqnl_Search
Write a C Program To Search a given number using linear search with their
complexity.
#include<stdio.h>
#include<conio.h>
#include<time.h>
void main()
{
int a[10],i,n,key,flg;
clock_tstime,etime;
double tm;
clrscr();
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter the %d Array elements ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
stime=clock();
for(i=0;i<n;i++)
{
if(a[i]==key)
flg=1;
}
etime=clock();
tm=(stime-etime)/CLK_TCK;
if(flg==1)
printf("Key element found\n");
else
printf("Key element not found\n");
printf("The duration taken to execute is %f",tm);
getch();
}
The searching mechanism proceeds from either of the two halves depending upon
whether the target element is greater or smaller than the central element. If the element is
smaller than the central element, then searching is done in the first half, otherwise searching is
done in the second half.
Set L to 0 and R to n: 1
else
Now, Am = T,
Sorting Techniques
In this chapter you will be dealing with the various sorting techniques and their
algorithms used to manipulate data structure and its storage. Sorting method can be
implemented in different ways - by selection, insertion method, or by merging. Various types
and forms of sorting methods have been explored in this tutorial.
What is sorting?
Sorting refers to the operation or technique of arranging and rearranging sets of data in
some specific order. A collection of records called a list where every record has one or more
fields. The fields which contain a unique value for each record is termed as the key field. For
example, a phone number directory can be thought of as a list where each record has three
fields - 'name' of the person, 'address' of that person, and their 'phone numbers'. Being unique
phone number can work as a key to locate any record in the list.
Sorting is the operation performed to arrange the records of a table or list in some order
according to some specific ordering criterion. Sorting is performed according to some key value
of each record.
The records are either sorted either numerically or alphanumerically. The records are
then arranged in ascending or descending order depending on the numerical value of the key.
Here is an example, where the sorting of a lists of marks obtained by a student in any particular
subject of a class.
Categories of Sorting
The techniques of sorting can be divided into two categories. These are:
Internal Sorting
External Sorting
Internal Sorting: If all the data that is to be sorted can be adjusted at a time in the main
memory, the internal sorting method is being performed.
External Sorting: When the data that is to be sorted cannot be accommodated in the memory
at the same time and some has to be kept in auxiliary memory such as hard disk, floppy disk,
magnetic tapes etc, then external sorting methods are performed .
The length of time spent by the programmer in programming a specific sorting program
Various sorting techniques are analyzed in various cases and named these cases as follows:
Best case
Worst case
Average case
Hence, the result of these cases is often a formula giving the average time required for a
particular sort of size 'n.' Most of the sort methods have time requirements that range from
O(nlog n) to O(n2).
Selection Sort
Merge Sort
Insertion Sort
Quick Sort
Heap Sort
Bubble Sort
Bubble Sort Algorithm is used to arrange N elements in ascending order, and for that,
you have to begin with 0th element and compare it with the first element. If the 0th element is
found greater than the 1st element, then the swapping operation will be performed, i.e., the
two values will get interchanged. In this way, all the elements of the array get compared.
1. algorithm Bubble_Sort(list)
2. Pre: list != fi
8. end if
9. end for
Write a C program to sort an array using bubble sort with their complexity
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,j,temp;
clrscr();
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter the elements %d array elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(j=1;j<n;j++)
{
for(i=0;i<n-j;i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf("Sorted Array elements are\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
getch();
}
Selection Sort
The selection is a straightforward process of sorting values. In this method, to sort the
data in ascending order, the 0th element is compared with all other elements. If the 0th
element is found to be greater than the compared element, the two values get interchanged. In
this way after the first iteration, the smallest element is placed at 0th position. The technique is
repeated until the full array gets sorted.
Merge Sort
Merge sort is another sorting technique and has an algorithm that has a reasonably
proficient space-time complexity - O(n log n) and is quite trivial to apply. This algorithm is based
on splitting a list, into two comparable sized lists, i.e., left and right and then sorting each list
and then merging the two sorted lists back together as one.
Merge sort can be done in two types both having similar logic and way of implementation.
These are:
Bottom up implementation
1. algorithm Merge_Sort(list)
2. Pre: list 6= fi
5. return list
6. end if
7. m <- list.Count = 2
Sort a given set of elements using the Merge sort method and determine the
time required to sort the elements. Repeat the experiment for different values
of n.
#include<stdio.h>
void disp( );
void mergesort(int,int,int);
void merge(int,int);
int a[50],n;
void main( )
{
int i;
clrscr( );
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter elements for an array:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nBefore Sorting the elements are:");
disp( );
merge(0,n-1);
printf("\nAfter Sorting the elements are:");
disp( );
getch( );
}
void disp( )
{
int i;
for(i=0;i<n;i++)
printf("%d ",a[i]);
}
void mergesort(int low,int mid,int high)
{
int t[50],i,j,k;
i=low;
j=mid+1;
k=low;
while((i<=mid) && (j<=high))
{
if(a[i]>=a[j])
t[k++]=a[j++];
else
t[k++]=a[i++];
}
while(i<=mid)
t[k++]=a[i++];
while(j<=high)
t[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=t[i];
}
void merge(int low,int high)
{
int mid;
if(low!=high)
{
mid=((low+high)/2);
merge(low,mid);
merge(mid+1,high);
mergesort(low,mid,high);
}
}
Quick Sort
Quick sort is one of the most famous sorting algorithms based on divide and conquers
strategy which results in an O(n log n) complexity. So, the algorithm starts by picking a single
item which is called pivot and moving all smaller items before it, while all greater elements in
the later portion of the list. This is the main quick sort operation named as a partition,
recursively repeated on lesser and greater sublists until their size is one or zero - in which case
the list is wholly sorted. Choosing an appropriate pivot, as an example, the central element is
essential for avoiding the severely reduced performance of O(n2).
1. algorithm Quick_Sort(list)
2. Pre: list 6= fi
5. return list
6. end if
9. if list[i] = pivot
10. equal.Insert(list[i])
11. end if
13. less.Insert(list[i])
14. end if
16. greater.Insert(list[i])
17. end if
Sort a given set of elements using the Quick sort method and determine the
time required to sort the elements. Repeat the experiment for different values
of n.
#include<stdio.h>
#include<time.h>
void qsort(int[],int,int);
int partition(int[],int,int);
void main()
{
int a[20],i,n;
clock_t s,e;
clrscr();
printf("Enter the value of n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
a[i]=rand()%100;
printf("\n The array elements before\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
s=clock();
delay(100);
qsort(a,0,n-1);
e=clock();
printf("\n Elements of the array after sorting are...\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n Time taken:%f",e-s/CLK_TCK);
getch();
}
Insertion Sort
Insertion sort is a to some extent an interesting algorithm with an expensive runtime
characteristic having O(n2). This algorithm can be best thought of as a sorting scheme which
can be compared to that of sorting a hand of playing cards, i.e., you take one card and then look
at the rest with the intent of building up an ordered set of cards in your hand.
1. algorithm Insertion_sort(list)
2. Pre: list 6= fi
4. unsorted <- 1
7. i à unsorted - 1
10. i <- i - 1
Binary Trees
This chapter explores one of the most important non-linear data structures, i.e., trees.
Various kinds of trees are available with different features. You will start learning with the most
important tree structure, i.e., the binary tree which is a finite set of elements that is either
empty or further divided into sub-trees.
Using arrays
Using Linked lists
Child node in a binary tree on the left is termed as 'left child node' and node in the right
is termed as the 'right child node.'
In the figure mentioned below, the root node 8 has two children 3 and 10; then this two
child node again acts as a parent node for 1 and 6 for left parent node 3 and 14 for right parent
node 10. Similarly, 6 and 14 has a child node.
A general tree is defined as a nonempty finite set T of elements called nodes such that:
A binary tree can be converted into an extended binary tree by adding new nodes to its
leaf nodes and to the nodes that have only one child. These new nodes are added in such a way
that all the nodes in the resultant tree have either zero or two children. It is also called 2 - tree.
The threaded Binary tree is the tree which is represented using pointers the empty
subtrees are set to NULL, i.e. 'left' pointer of the node whose left child is empty subtree is
normally set to NULL. These large numbers of pointer sets are used in different ways.
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int info;
struct node *llink;
struct node *rlink;
};
typedefstruct node *NODE;
NODE insert(intitem,NODE root)
{
if(root==NULL)
{
root=(NODE)malloc(sizeof(struct node));
root->info=item;
root->llink=root->rlink=NULL;
}
else
if(item==root->info)
printf("Duplicate entry\n");
else
if(item<root->info)
root->llink=insert(item,root->llink);
else
root->rlink=insert(item,root->rlink);
return root;
}
void preorder(NODE root)
{
if(root!=NULL)
{
printf("%d\t",root->info);
preorder(root->llink);
preorder(root->rlink);
}
}
voidpostorder(NODE root)
{
if(root!=NULL)
{
postorder(root->llink);
postorder(root->rlink);
printf("%d\t",root->info);
}
}
voidinorder(NODE root)
{
if(root!=NULL)
{
inorder(root->llink);
printf("%d\t",root->info);
inorder(root->rlink);
}
}
void main()
{
NODE root=NULL;
intchoice,item;
clrscr();
printf("Operation on tree traversal\n");
for(;;)
{
printf("\n***MENU***\n");
printf("1.Insert\n2.Preorder\n3.Postorder\n4.Inorder\n5.Quit\n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("Enter the item to be inserted\n");
scanf("%d",&item);
root=insert(item,root);
break;
case 2:preorder(root);
break;
case 3:postorder(root);
break;
case 4:inorder(root);
break;
case 5:exit(0);
break;
default:printf("Invlid choice\n");
}
}
}
No.1 Write a C program to create a file that contains at least 5 records which
consists of
Book No,Book Name,Author,Publisher,and price.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *ptr;
intbookid,i;
charbookname[20];
char authorname[20];
char publisher[20];
int price;
clrscr();
ptr=fopen("extra16.c","w");
if(ptr==NULL)
{
printf("Error in opening file");
exit(0);
}
for(i=0;i<5;i++)
{
printf("Enter the bookid,bookname,authorname,pulisher,price:\n");
scanf("%d%s%s%s%d",&bookid,&bookname,&authorname,&publisher);
fprintf(ptr,"%d\t%s\t%s\t%s\t%d\n",bookid,bookname,authorname,publisher);
}
fclose(ptr);
getch();
}
#include<stdio.h>
void main()
{
FILE *ptr;
char ch;
int count=0;
clrscr();
ptr=fopen("extra10.c","r");
if(ptr==NULL)
{
printf("\nError in opening file");
exit(0);
}
while(!feof(ptr))
{
ch=getc(ptr);
count++;
printf("%c",ch);
}
printf("The number of characters are:%d",count);
fclose(ptr);
getch();
}
Write a C program to display the contents of the file created in program No.1
in the following format
Book_ID Book_Name Book_Author Publisher Price
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *ptr;
int book_id,i;
char book_name[20];
char author_name[20];
char publisher[20];
int price;
clrscr();
ptr=fopen("extra21.c","r");
if(ptr==NULL)
{
printf("Error in file opening");
exit(0);
}
printf("\nBook_ID Book_Name Book_Author Publisher Price\n");
for(i=0;i<=5;i++)
{
fscanf(ptr,"%d\t%s\t%s\t%s\t%d\n",&book_id,&book_name,&author_name,&publisher,&price
);
printf("%d\t%s\t%s\t%s\t%d\n",book_id,book_name,author_name,publisher,price);
}
fclose(ptr);
getch();
}
Write a C program to copy one file to another file using command line
argument
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(intargc,char *argv[])
{
charch;
inti,n;
FILE *ptr1,*ptr2;
clrscr();
if(argc>0)
{
ptr1=fopen(argv[1],"r");
ptr2=fopen(argv[2],"w");
ch=getc(ptr1);
while(!feof(ptr1))
{
putc(ch,ptr2);
ch=getc(ptr1);
}
}
fclose(ptr1);
fclose(ptr2);
printf("\nThe file is copied\n");
ptr1=fopen(argv[2],"r");
printf("the copied file is\n");
while((ch=getc(ptr2))!=EOF)
printf("%c",ch);
fclose(ptr2);
getch();
}
Thank You
its me Only