Sie sind auf Seite 1von 10

Master of Science in Information Technology (MScIT-NEW) Semester 1 MT0033 DATA STRUCTURES USING C 4 Credits

(Book ID: B0701 & B0702) Assignment Set 1 (40 Marks)

Book-ID: B0701 Define array? Write a program to store 10 salesmens amount in an array and find out total sale & best sales amount.
Arrays are used in C to represent structures of consecutive elements of the same type. The definition of a (fixed-size) array has the following syntax: int array[100]; which defines an array named array to hold 100 values of the primitive type int. If declared within a function, the array dimension may also be a non-constant expression, in which case memory for the specified number of elements will be allocated. The primary facility for accessing the values of the elements of an array is the array subscript operator. To access the i-indexed element of array, the syntax would be array[i], which refers to the value stored in that array element. Array subscript numbering begins at 0. The largest allowed array subscript is therefore equal to the number of elements in the array minus 1. To illustrate this, consider an array a declared as having 10 elements; the first element would be a[0] and the last element would be a[9]. C provides no facility for automatic bounds checking for array usage. Though logically the last subscript in an array of 10 elements would be 9, subscripts 10, 11, and so forth could accidentally be specified, with undefined results. A constant value is required for the dimension in a declaration of a static array. A desired feature is the ability to set the length of an array dynamically at run-time instead: int n = ...; int a[n]; a[3] = 10; When the dynamically-allocated memory is no longer needed, it should be released back to the run-time system. This is done with a call to the free function. It takes a single parameter: a pointer to previously allocated memory. C supports arrays of multiple dimensions, which are stored in row-major order. Technically, C multidimensional arrays are just one-dimensional arrays whose elements are arrays. The syntax for declaring multidimensional arrays is as follows: int array2d[ROWS][COLUMNS]; (where ROWS and COLUMNS are constants); this defines a two-dimensional array. Reading the subscripts from left to right, array2d is an array of length ROWS, each element of which is an array of COLUMNS ints. To access an integer element in this multidimensional array, one would use array2d[4][3]

Write a program to store 10 salesmens amount in an array and find out total sale & best sales amount.
#include <iostream.h> #include <conio.h> main ( ) { const int n = 10;

int sale_amt [100]; tot_amt; best = 0; clrscr ( ) /* storing values in an array */ for (i = 0; i< = n ; i + +) { printf(Enter sales amount: n); scanf(%d, &sale_amt[i]); } /* Calculate the total sale & find out best amount */ tot_sale = 0; best = 0; for (i = 0; i<n; i+ +) { prntf( n sale amount %d , = %d , i, sale_amt [i]); tot_amt = tot_amt + sale_amt[i]; if sale_amt[i] > best best = sale_amt [i]; } /* Printing Total and Best Sale amount */ printf( n Total sale amount = %d , tot_amt); printf( n Best sale amount = %d ,best); }

What do you mean by a queue? Write C program to implement an ordinary queue.


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 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. Queues provide services in computer science, transport, and operations research where various entities such as data, objects, persons, or events are stored and held to be processed later. In these contexts, the queue performs the function of a buffer. Queues are common in computer programs, where they are implemented as data structures coupled with access routines, as an abstract data structure or in object-oriented languages as classes. Common implementations are circular buffers and linked lists.

# #include <stdio.h> #include<ctype.h> # define MAXSIZE 200 int q[MAXSIZE]; int front, rear; void main() { void add(int); int del();

int will=1,i,num; front =0; rear = 0; clrscr(); printf(" Program for queue demonstration through array

"); while(will ==1) { printf(" MAIN MENU: 1.Add element to queue 2.Delete element from the queue "); scanf("%d",&will); switch(will) { case 1: printf(" Enter the data... "); scanf("%d",&num); add(num); break; case 2: i=del(); printf(" Value returned from delete function is %d ",i); break; default: printf("Invalid Choice ... "); } printf(" Do you want to do more operations on Queue ( 1 for yes, any other key to exit) "); scanf("%d" , &will); } //end of outer while } //end of main

void add(int a) { if(rear>MAXSIZE) { printf(" QUEUE FULL "); return; } else { q[rear]=a; rear++; printf(" Value of rear = %d and the value of front is %d",rear,front); } } int del() { int a; if(front == rear) { printf(" QUEUE EMPTY "); return(0); } else { a=q[front]; front++; } return(a); }

Book-ID: B0702 What is the Bellman-Ford Algorithm? State and explain


Bellman-Ford algorithm solves the single-source shortest-path problem in the general case in which edges of a given digraph can have negative weight as long as G contains no negative cycles. This algorithm, like Dijkstra's algorithm uses the notion of edge relaxation but does not use with greedy method. Again, it uses d[u] as an upper bound on the distance d[u, v] from u to v. The algorithm progressively decreases an estimate d[v] on the weight of the shortest path from the source vertex s to each vertex v in V until it achieve the actual shortest-path. The algorithm returns Boolean TRUE if the given digraph contains no negative cycles that are reachable from source vertex s otherwise it returns Boolean FALSE.

BELLMAN-FORD (G, w, s) INITIALIZE-SINGLE-SOURCE (G, s) for each vertex i = 1 to V[G] - 1 do for each edge (u, v) in E[G] do RELAX (u, v, w) For each edge (u, v) in E[G] do if d[u] + w(u, v) < d[v] then return FALSE return TRUE

What do you mean by a Graph? How graphs are represented? Explain


A graph is a collection of vertices V and a collection of edges E consisting of pairs of vertices. Think of vertices as locations. The set of vertices is the set of all the possible locations. In this analogy, edges represent paths between pairs of those locations. The set E contains all the paths between the locations.

Graph Representation The graph is normally represented using that analogy. Vertices are points or circles, edges are lines between them. In this example graph: V = {1, 2, 3, 4, 5, 6} E = {(1,3), (1,6), (2,5), (3,4), (3,6)}. Each vertex is a member of the set V. A vertex is sometimes called a node. Each edge is a member of the set E. Note that some vertices might not be the end point of any edge. Such vertices are termed isolated. Sometimes, numerical values are associated with edges, specifying lengths or costs; such graphs are called edge-weighted graphs (or weighted graphs). The value associated with an edge is called the weight of the edge. A similar definition holds for node-weighted graphs. The choice of representation of a graph is important, as different representations have very different time and space costs. The vertices are generally tracked by numbering them, so that one can index them just by their number. Thus, the representations focus on how to store the edges. Edge List The most obvious way to keep track of the edges is to keep a list of the pairs of vertices representing the edges in the graph. This representation is easy to code, fairly easy to debug, and fairly space efficient. However, determining the edges incident to

a given vertex is expensive, as is determining if two vertices are adjacent. Adding an edge is quick, but deleting one is difficult if its location in the list is not known. For weighted graphs, this representation also keeps one more number for each edge, the edge weight. Extending this data structure to handle directed graphs is straightforward. Representing multigraphs is also trivial. Adjacency Matrix A second way to represent a graph utilized an adjacency matrix. This is a N by N array (N is the number of vertices). The i,j entry contains a 1 if the edge (i,j) is in the graph; otherwise it contains a 0. For an undirected graph, this matrix is symmetric. This representation is easy to code. Its much less space efficient, especially for large, sparse graphs. Debugging is harder, as the matrix is large. Finding all the edges incident to a given vertex is fairly expensive (linear in the number of vertices), but checking if two vertices are adjacent is very quick. Adding and removing edges are also very inexpensive operations. For weighted graphs, the value of the (i,j) entry is used to store the weight of the edge. For an unweighted multigraph, the (i,j) entry can maintain the number of edges between the vertices. For a weighted multigraph, its harder to extend this. Implicit Representation For some graphs, the graph itself does not have to be stored at all. For example, for the Knight moves and Overfencing problems, it is easy to calculate the neighbors of a vertex, check adjacency, and determine all the edges without actually storing that information, thus, there is no reason to actually store that information; the graph is implicit in the data itself. If it is possible to store the graph in this format, it is generally the correct thing to do, as it saves

Master of Science in Information Technology (MScIT-NEW) Semester 1 MT0033 DATA STRUCTURES USING C 4 Credits
(Book ID: B0701 & B0702) Assignment Set 2 (40 Marks) Book-ID: B0701 Explain the Adjacency lists with suitable example
Adjacency List The third representation of a matrix is to keep track of all the edges incident to a given vertex. This can be done by using an array of length N, where N is the number of vertices. The i-th entry in this array is a list of the edges incident to i-th vertex (edges are represented by the index of the other vertex incident to that edge). This representation is much more difficult to code, especially if the number of edges incident to each vertex is not bounded, so the lists must be linked lists (or dynamically allocated). Debugging this is difficult, as following linked lists is more difficult. However, this representation uses about as much memory as the edge list. Finding the vertices adjacent to each node is very cheap in this structure, but checking if two vertices are adjacent requires checking all the edges adjacent to one of the vertices. Adding an edge is easy, but deleting an edge is difficult, if the locations of the edge in the appropriate lists are not known. Extend this representation to handle weighted graphs by maintaining both the weight and the other incident vertex for each edge instead of just the other incident vertex. Multigraphs are already representable. Directed graphs are also easily handled by this representation, in one of several ways: store only the edges in one direction, keep a separate list of incoming and outgoing arcs, or denote the direction of each arc in the list. Example The adjacency list representation of the example undirected graph is as follows: Vertex Adjacent Vertices 1 3, 6 2 5 3 6, 4, 1 4 3 5 2 6 3, 1

Write the algorithm and C program for sorting the numbers in ascending order using quick sort technique.
Algorithm

Quicksort (int A[], int X, int I) { int L, R, V 1. If (IX) { 2. V= A[I], L = X-I, R = I; 3. For (;;) { 4. While (A[ + + L] V); 5. While (A[--R] V); 6. If (L = R) /* left & right ptrs. have crossed */ 7. break; 8. Swap (A, L, R) /* Swap A[L] & A[R] */ } 9. Swap (A, L, I) 10. Quicksort (A, X, L-1) 11. Quicksort (A, L + 1, I) }

C program to sort the numbers in ascending order using quick sort.


#include<stdio.h> /* Function to partition the array for quick sort*/ int partition(int a[],int low, int high) { int i,j,temp,key; key=a[low]; i=low+1; j=high; while(1) { while(i<high&&key>=a[i]) i++; while(key<a[j]) j; if(i<j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } else { temp=a[low]; a[low]=a[j]; a[j]=temp; } } } /* function to sort the numbers in ascending order using quick sort */ void qucksort(int a[], int low, int high) { int j; if(low<high) { j=partition(a,low,high); /* partion the array into 2 subtables */ quicksort(a,low,j-1) /* Sort the left part of the array */ quicksort(a,j+1,high); /* Sort the right part of the array */ } } void main() { int I,n,a[20]; printf(Enter the value for n n); scanf(%d,&n); printf(Enter the number to be sorted n); for(i=0;i<n;i++) scanf(%d, &a*i+); quicksort(a,0,n-1); printf(The sorted array is n); for(i=0;i<n;i++)

printf(%dn,a*i+); }

Book-ID: B0702 What is the significance of a Depth First Search (DFS)? How it is implemented?
Form a one-element queue consisting of the root node. Until the queue is empty or the goal has been reached, determine if the first element in the queue is the goal node. If the first element is the goal node, do nothing. If the first element is not the goal node, remove the first element from the queue and add the first elements children, if any, to the front of the queue. If the goal node has been found, announce success, otherwise announce failure. Depth First Search (DFS) Implementation The most obvious solution to code is to add queens recursively to the board one by one, trying all possible queen placements. It is easy to exploit the fact that there must be exactly one queen in each column: at each step in the recursion, just choose where in the current column to put the queen. 1. search(col) 2. if filled all columns 3. print solution and exit 4. for each row 5. if board(row, col) is not attacked 6. place queen at (row, col) 7. search(col+1) 8. remove queen at (row, col) Calling search(0) begins the search. This runs quickly, since there are relatively few choices at each step: once a few queens are on the board, the number of non-attacked squares goes down dramatically. This is an example of depth first search, because the algorithm iterates down to the bottom of the search tree as quickly as possible: once k queens are placed on the board, boards with even more queens are examined before examining other possible boards with only k queens. This is okay but sometimes it is desirable to find the simplest solutions before trying more complex ones. Depth first search checks each node in a search tree for some property. The search tree might look like this:

The algorithm searches the tree by going down as far as possible and then backtracking when necessary, making a sort of outline of the tree as the nodes are visited. Pictorially, the tree is traversed in the following manner:

4. Explain the following a) Sequential files


A sequential file is the most primitive of all file structures. It has no directory and no linking pointers. The records are generally organised in lexicographic order on the value of some key. In other words, a particular attribute is chosen whose value will determine the order of the records. Sometimes when the attribute value is constant for a large number of records a second key is chosen to give an order when the first key fails to discriminate. The implementation of this file structure requires the use of a sorting routine. Its main advantages are: (1) it is easy to implement; (2) it provides fast access to the next record using lexicographic order. Its disadvantages: (1) it is difficult to update inserting a new record may require moving a large proportion of the file; (2) random access is extremely slow. Sometimes a file is considered to be sequentially organised despite the fact that it is not ordered according to any key. Perhaps the date of acquisition is considered to be the key value, the newest entries are added to the end of the file and therefore pose no difficulty to updating.

b) Inverted files
An inverted file is a file structure in which every list contains only one record. Remember that a list is defined with respect to a keyword K, so every K-list contains only one record. This implies that the directory will be such that ni = hi for all i, that is, the number of records containing Ki will equal the number of Ki-lists. So the directory will have an address for each record containing Ki . For document retrieval this means that given a keyword we can immediately locate the addresses of all the documents containing that keyword. For the previous example let us assume that a non-black entry in the field corresponding to an attribute indicates the presence of a keyword and a black entry its absence. Then the directory will point to the file in the way shown in Figure 6.3. The definition of an inverted files does not require that the addresses in the directory are in any order. However, to facilitate operations such as conjunction (and) and disjunction (or) on any two inverted lists, the addresses are normally kept in record number order. This means that and and or operations can be performed with one pass through both lists. The penalty we pay is of course that the inverted file becomes slower to update.

Fig. 6.3: An inverted file

Das könnte Ihnen auch gefallen