18
Data Structure Using ‘C’ Assignment No: 01 1. Write a program in ‘C’ to read N numbers and print them in descending order. Sol:- #include<stdio.h> #include<conio.h> int main() { Int sort [n], i, j, t, n; Clrscr (); Printf ("\n\nEnter Numbers"); scanf ("%d", &n); Printf ("Enter number to be print in descending order"); For (i=0;i<n;i++) Scanf ("%d",&sort[i]); for(i=0;i<n;i++) { for (j=i+1;j<n;j++) { if(sort[i]>sort[j]) { t=sort[i]; Sort[i] =sort[j]; Sort[j] =t; }}} printf ("Numbers in Descending Order Are :"); For (i=n-1;i>=0;i--) { printf ("%d\n", sort[i]); } getch (); } 2. Discuss the properties of ADT. Sol: - ADT belongs to abstract data type. It is characterized by the following properties:- It exports a type.

Data Structure

Embed Size (px)

Citation preview

Page 1: Data Structure

Data Structure Using ‘C’ Assignment No: 01

1. Write a program in ‘C’ to read N numbers and print them in

descending order.

Sol:- #include<stdio.h>

#include<conio.h>int main(){Int sort [n], i, j, t, n;Clrscr ();Printf ("\n\nEnter Numbers");scanf ("%d", &n);Printf ("Enter number to be print in descending order");For (i=0;i<n;i++)Scanf ("%d",&sort[i]);for(i=0;i<n;i++){for (j=i+1;j<n;j++){if(sort[i]>sort[j]){t=sort[i];Sort[i] =sort[j];Sort[j] =t;}}}printf ("Numbers in Descending Order Are :");For (i=n-1;i>=0;i--){printf ("%d\n", sort[i]);}getch ();}

2. Discuss the properties of ADT.

Sol: - ADT belongs to abstract data type. It is characterized by the following properties:-

It exports a type. It exports a set of operations. This set is called interface. Operations of the interface are the one and only access mechanism to the

type’s data structure. Axioms and preconditions define the application domain of the type.

With the first property of ADT it is possible to create

more than one instant of an ADT.

Page 2: Data Structure

3. Write a note on i) Binary tree ii) Hash tables.

Sol:- i) Binary tree:- In computer science, a binary tree is a tree data structure in which

each node has at most two children. Typically the child nodes are called left and right.

In binary tree the upper node is called as root. Roots are larger from its childe. Binary

trees are commonly used to implement binary search trees and binary heaps.

Notes:-

Each node contains only one element.

The right childe could be empty but not left is empty and right have an element.

No of nodes on lowest level should be 2i-2.

ii) Hash tables:- A hash table, or a hash map, is a data structure that

associates keys with values. The primary operation it supports efficiently is a

lookup: given a key (e.g. a person's name), find the corresponding value (e.g.

that person's telephone number). It works by transforming the key using a hash

function into a hash, a number that is used as an index in an array to locate the

desired location ("bucket") where the values should be.

Hash tables support the efficient insertion of

new entries, in expected O(1) time. The time spent in searching depends on the

hash function and the load of the hash table; both insertion and search approach

O(1) time with well chosen values and hashes.

4. Write a ‘C’ program to implement the stack operations using arrays.

Sol:- C program to implement the stack using arrays is as following:-

#include<stdio.h>

#include<conio.h>

#include<process.h>

#define STACK_SIZE 5

5. What is queue? Explain different types of queues.

Sol:-Queue is a special type of data structure. A queue is a particular kind of

collection in which the entities in the collection are kept in order and the

principal (or only) operations on the collection are the addition of entities to the

rear terminal position and removal of entities from the front terminal position.

This makes the queue a First-In-First-Out (FIFO) data structure. In a FIFO data

structure, the first element added to the queue will be the first one to be

Page 3: Data Structure

removed. This is equivalent to the requirement that whenever an element is

added, all elements that were added before have to be removed before the new

element can be invoked. A queue is an example of a linear data structure. There

are four types of queue which are:-

Ordinary Queue:- It operates on FIFO rule i.e. the item will be inserted

first will be removed first.

Double Ended Queue:- Deque (short of double-ended queue) is an

abstract list type data structure, also called a head-tail linked list, for

which elements can be added to or removed from the front (head) or back

(tail).

Circular Queue:- A circular is a data structure that uses a single, fixed-

size queue as if it were connected end-to-end. This structure lends itself

easily to buffering data streams.

Priority Queue:- A priority queue is an abstract data type in computer

programming that supports the following three operations:

1. Insert With Priority: add an element to the queue with an associated

priority

2. Get Next: remove the element from the queue that has the highest

priority, and return it (also known as "Pop Element(Off)", or "Get

Minimum")

3. Peek At Next (optional): look at the element with highest priority

without removing it.

6. Explain the Circular singly linked list with neat diagram.

Sol:-In a circularly-linked list, the first and last nodes are linked together. This can

be done for both singly and doubly linked lists. To traverse a circular linked list,

we begin at any node and follow the list in either direction until we return to the

original node. Viewed another way, circularly-linked lists can be seen as having

no beginning or end. This type of list is most useful for managing buffers for

data ingest, and in cases where you have one object in a list and wish to iterate

through all other objects in the list in no particular order. The pointer pointing to

the whole list may be called the access pointer.

Page 4: Data Structure

A circularly-linked list

7. Discuss the various graphs with neat diagram.

Sol:- In computer science, a graph is a kind of data structure, specifically an abstract data type (ADT), that consists of a set of nodes (also called vertices) and a set of edges that establish relationships (connections) between the nodes. The graph ADT follows directly from the graph concept from mathematics.

Informally, G=(V,E) consists of vertices, the elements of V, which are connected by edges, the elements of E. Formally, a graph, G, is defined as an ordered pair, G=(V,E), where V is a set (usually finite) and E is a set consisting of two element subsets of V.

The graphs can be represented in two ways. One is adjacency matrix and adjacency list.

For A----------->B | ^ | | | | V | C ------------

Adjacency Matrix

A B C A 0 1 1 B 0 0 0 C 0 1 0

Adjacency List

A ----> | B | ----> | C | ---- NULL B ----> ---- NULL C ----> | B | ---- NULL

Example let us consider the following graph

8. Explain with example how to delete a node from the tree.

Each element in an internal node acts as a separation value for two subtrees, and when such an element is deleted, two cases arise. In the first case, both of the two child nodes to the left and right of the deleted element have the minimum number of elements, namely L-1. They can then be joined into a single node with 2L-2 elements, a number which does not exceed U-1 and so is a legal node. Unless it is known that this particular B-tree does not contain duplicate data, we must then also (recursively) delete the element in question from the new node.

Page 5: Data Structure

In the second case, one of the two child nodes contains more than the minimum number of elements. Then a new separator for those subtrees must be found. Note that the largest element in the left subtree is the largest element which is still less than the separator. Likewise, the smallest element in the right subtree is the smallest element which is still greater than the separator. Both of those elements are in leaf nodes, and either can be the new separator for the two subtrees.

If the value is in an internal node, choose a new separator (either the largest element in the left subtree or the smallest element in the right subtree), remove it from the leaf node it is in, and replace the element to be deleted with the new separator.

This has deleted an element from a leaf node, and so is now equivalent to the previous case.

Page 6: Data Structure

Data Structure Using ‘C‘ Assignment No: 02

1. Define Data structure? Explain its three comments.

Sol: - Data structure:- A data structure in computer science is a way of storing data in a computer so that it can be used efficiently. It is an organization of mathematical and logical concepts of data. Often a carefully chosen data structure will allow the most efficient algorithm to be used. The choice of the data structure often begins from the choice of an abstract data type. A well-designed data structure allows a variety of critical operations to be performed, using as few resources, both execution time and memory space, as possible. Data structures are implemented by a programming language as data types and the references and operations they provide.

Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to certain tasks. For example, B-trees are particularly well-suited for implementation of databases, while networks of machines rely on routing tables to function.

In the design of many types of computer program, the choice of data structures is a primary design consideration. Experience in building large systems has shown that the difficulty of implementation and the quality and performance of the final result depends heavily on choosing the best data structure. After the data structures are chosen, the algorithms to be used often become relatively obvious. Sometimes things work in the opposite direction — data structures are chosen because certain key tasks have algorithms that work best with particular data structures. In either case, the choice of appropriate data structures is crucial.

This insight has given rise to many formalized design methods and programming languages in which data structures, rather than algorithms, are the key organizing factor. Most languages feature some sort of module system, allowing data structures to be safely reused in different applications by hiding their verified implementation details behind controlled interfaces. Object-oriented programming languages such as C++ and Java in particular use classes for this purpose.

Since data structures are so crucial, many of them are included in standard libraries of modern programming languages and APIs, such as C++'s containers, the Java Collections Framework, and the Microsoft .NET Framework.

The fundamental building blocks of most data structures are arrays, records, discriminated unions, and references. For example, the nullable reference, a reference which can be null, is a combination of references and discriminated unions, and the simplest linked data structure, the linked list, is built from records and nullable references.

Data structures represent implementations or interfaces: A data structure can be viewed as an interface between two functions or as an implementation of methods to access storage that is organized according to the associated data type.

Page 7: Data Structure

2. Explain the pre and Post conditions with a suitable example.

3. Explain different Applications of stack.

In computer science, a stack is an abstract data type and data structure

based on the principle of Last In First Out (LIFO). Stacks are used

extensively at every level of a modern computer system. For example,

a modern PC uses stacks at the architecture level, which are used in

the basic design of an operating system for interrupt handling and

operating system function calls. Among other uses, stacks are used to

run a Java Virtual Machine, and the Java language itself has a class

called "Stack", which can be used by the programmer. The stack is

ubiquitous.

Application of stack

Expression evaluation and syntax parsing

Calculators employing reverse Polish notation use a stack structure to hold values. Expressions can be represented in prefix, postfix or infix notations. Convers

Expressions can be represented in prefix, postfix or infix notations. Conversion from one form of the expression to another form needs a stack. Many compilers use a stack for parsing the syntax of expressions, program blocks etc. before translating into low level code. Most of the programming languages are context-free languages allowing them to be parsed with stack based machines.

Runtime memory management

A number of programming languages are stack-oriented, meaning they define most basic operations (adding two numbers, printing a character) as taking their arguments from the stack, and placing any return values back on the stack. For example, PostScript has a return stack and an operand stack, and also has a graphics state stack and a dictionary stack.

Forth uses two stacks, one for argument passing and one for subroutine return addresses. The use of a return stack is extremely commonplace, but the somewhat unusual use of an argument stack for a human-readable programming language is the reason Forth is referred to as a stack-based language.

Page 8: Data Structure

4. Write a note on Double Ended queues.

In computer science theory, a deque (short for double-ended queue—usually pronounced deck) is an abstract list type data structure, also called a head-tail linked list, for which elements can be added to or removed from the front (head) or back (tail).Deque is sometimes written dequeue, but this use is generally deprecated in technical literature or technical writing because dequeue is also a verb meaning "to remove from a queue". Nevertheless, several libraries and some writers, such as Aho, Hopcroft, and Ullman in their textbook Data Structures and Algorithms, spell it dequeue. DEQ and DQ are also used.

This differs from the queue abstract data type or First-In-First-Out List (FIFO), where elements can only be added to one end and removed from the other. This general data class has some possible sub-types:

An input-restricted deque is one where deletion can be made from both ends, but input can only be made at one end.

An output-restricted deque is one where input can be made at both ends, but output can be made from one end only.

Both the basic and most common list types in computing, the queues and stacks can be considered specializations of deques, and can be implemented using deques.

5. Write a ‘C’ program to implement deque using circular linked list.

Sol: - Program to implement deque using circular linked list:-

#include<stdio.h>

#include<conio.h>

#include<alloc.h>

#include<process.h>

struct node

{int info;

Struct node*link:

};

typedef struct node*NODE;

void main()

{NODE last;

int choice,item;

last=NULL;

for(;;)

{printf("1:Insert_Front,2:Insert_rear\n");

Page 9: Data Structure

printf("3:Delet_Front,4:Delet_rear\n");

printf("5:Display,6:Exit\n");

printf("Enter the choice\n");

scanf("%d",choice);

switch(choice)

{case 1:

printf("Enter the item to be inserted\n");

scanf("%d",&item);

last=insert_front(item,last);

break;

case 2:

printf("Enter the item to be inserted\n");

scanf ("%d",item);

last=insert_rear(item,last);

break;

case 3:

case 4:

last=delet_rear(last)

break;

case 5:

displaya(last);

break;

case 6:

exit(0);

break;

default:

exit(0);

}}}

getch();

}

Page 10: Data Structure

6. Explain various operations that can be performed on binary tree.

Sol:- A Binary tree is a tree in which no node have more than two sub tree. In other word A tree in which every parent has one or two children (but not more then that) is called as binary tree.

The root component of binary tree is the forefather of all children. But it can have only up to two children one right child and left child. These children can become fathers, grandfather, great grandfather and son.

The operations which can be on a binary tree is Insertion – Insert a given item into a tree Traversal – Visiting the nodes of the tree one by one. Search – Search for the specific item. Copying – To obtain exact copy of the given tree. Deletion – To delete a node from the tree.

7. Write a note on Binary Search Tree (BST).

In computer science, a binary search tree (BST) is a binary tree data structure which has the following properties:

each node (item in the tree) has a distinct value; both the left and right subtrees must also be binary search trees; the left subtree of a node contains only values less than the node's value; the right subtree of a node contains only values greater than or equal to the node's value.

The major advantage of binary search trees over other data structures is that the related sorting algorithms and search algorithms such as in-order traversal can be very efficient.

Binary search trees can choose to allow or disallow duplicate values, depending on the implementation.

Binary search trees are a fundamental data structure used to construct more abstract data structures such as sets, multisets, and associative arrays.

Searching a binary tree for a specific value can be a recursive or iterative process. This explanation covers a recursive method.

We begin by examining the root node. If the tree is null, the value we are searching for does not exist in the tree. Otherwise, if the value equals the root, the search is successful. If the value is less than the root, search the left subtree. Similarly, if it is greater than the root, search the right subtree. This process is repeated until the value is found or the indicated subtree is null. If the searched value is not found before a null subtree is reached, then the item must not be present in the tree.

8. Write a ‘C’ program to sort an array of 10 elements using Bubble sort

algorithm.

Sol: - Bubble sort algorithm

Page 11: Data Structure

Input: list [] of N=10 items in random order

Output: list [] of N=10 items in sorted in ascending order.

1. SWAP=TRUE

PASS=0/

2. WHILE SWAP=TRUE DO

BEGIN

2.1 FOR I = 0 TO (N-PASS ) DO

BEGIN

2.1.1 IF A[I] > A[I+1]

BEGIN

TMP = A[I]

A[I] = A[I+1]

A[I+1] =TMP

SWAP = TRUE

END

ELSE

SWAP = FALSE

2.1.2 PASS=PASS+1

END

END

PROGRAM FOR BUBBLE SORT ALGORITHM:-

#include<stdio.h>

#include<conio.h>

void main()

{ int n,temp,i,j;

int arr[20];

clrscr();

printf("Enter no");

scanf("%d",&n);

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

{ printf("Enter the value in array : ");

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

}

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

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

{

Page 12: Data Structure

if (arr[i]>arr[j]);

{ temp=arr[i];

arr[i]=arr[j];

arr[j]=temp; }}}

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

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

getch(); }