id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
24,200 | notes there are bunch of junctions (nodes in the graphand bunch of pipes (edges in the graphconnecting the junction the pipe will only allow water to flow one way (the graph is directedeach pipe has also has capacity (the weight of the edge)representing the maximum amount of water that can flow through the pipe finallywe pour an infinite amount of water into the source vertex the problem is to find the maximum flow of the graph the maximum amount of water that will flow to the sink below is an example of network flow graph figure simple network flow graph there are currently no water flowing / / / / / it is fairly easy to see that the maximum flow in the figure is we can flow units of water from units of water from tand units of water from this gives flow of and since all incoming edge to the sink are saturatedthis is indeed the maximum flow note in the examplenot all pipe are saturated with water ford fulkerson method it was easy to see the solution in the above examplebut how do we find the solution in generalone idea is to keep finding path from to along pipes which still has some capacities remaining and push as much flow from to as possible we will then terminate once we can' find any more path this idea seem to work since it is exactly how we found the maximum flow in the example howeverthere is one problem we cannot guarantee which path we'll find first in factif we picked the wrong paththe whole algorithm will go wrong for examplewhat happens if lovely professional university |
24,201 | the first path we found was if we push as much flow as possiblethen we end up with the followingnotes figure we have pushed flow along the path / / / / / now we have run into problemour only options left are to push unit of water along the path and unit of water along after thatwe won' be able to find any more path from to tyetwe have only found flowwhich is not he maximum flow thusthe idea is not optimal since it depends on how we picked our path while we can try to find "goodpathpicking algorithmit would be nice if the algorithm is not dependent on the paths we chose crucial observation is that there is actually another path from to other than the two that we mentioned abovesuppose we redirect units of water from to tthis will decrease the amount of water running through the pipe (atto now we have path from in which we can flow units of waterthe graph now looks as followsfigure the bolded edge indicate which pipe has their flow adjusted / / / / / it is now easy to see that we can push unit of water along to obtain the maximum flow of if we carefully study in the figure what we have essentially done is to flow unit of water along aand then push back unit of water from band finally redirect the pushed back flow along to the sink so the key to completing the algorithm is the idea of pushing back flow if we have units of water flowing in the pipe (uv)then we can pretend there is pipe (vuwith capacity when we are trying to find path from to this is the concept of residual graph the residual graph of network flow is essentially the network graph except that for every edge (uvthat currently carries unit of waterthere is lovely professional university |
24,202 | notes an edge (vuwith capacity in the residual graph figure shows the residual graph after finding our first pathfigure the dashed edges are the edges we added in the residual graph / / / / / the capacity of the dashed edge is the same as the amount of water carried by the solid edge in the opposite direction so here is an algorithm to find the maximum flowfirst construct the residual graph (in the beginningthe residual graph is the same as the network graphwhile there exists path from to in the residual graphwe flow water through one of the path ( path in the residual graph is called an augmenting pathwe then adjust the residual graph accordingly once we can no longer find any more path in the residual graphwe have found the maximum flow comparison networks suppose we have directed network (vedefined by set of nodes (or vertexesand set of arcs (or edgeseach arc ( ,jin has an associated nonnegative capacity uij also we distinguish two special nodes in ga source node and sink node for each in we denote by (iall the arcs emanating from node let max uij by ( ,jin let us also denote the number of vertexes by and the number of edges by we wish to find the maximum flow from the source node to the sink node that satisfies the arc capacities and mass balance constraints at all nodes representing the flow on arc ( ,jin by xij we can obtain the optimization model for the maximum flow problemmaximize (xx ij es subject to \{stij : ij : <xij <uij (ij(ije vector (xijwhich satisfies all constraints is called feasible solution ora flow (it is not necessary maximalgiven flow we are able to construct the residual network with respect to this flow according to the following intuitive idea suppose that an edge ( ,jin carries xij units of flow we define the residual capacity of the edge ( ,jas rij uij xij this means that we can send an additional rij units of flow from vertex to vertex we can also cancel the existing flow xij on the arc if we send up xij units of flow from to over the arc ( ,jsogiven feasible flow we define the residual network with respect to the flow as follows suppose we have network (vea feasible solution engenders new (residualnetwork lovely professional university |
24,203 | which we define by gx (vex)where ex is set of residual edges corresponding to the feasible solution notes what is exwe replace each arc ( ,jin by two arcs ( , )( , )the arc ( ,jhas (residualcapacity rij uij xijand the arc ( ,ihas (residualcapacity rji=xij then we construct the set ex from the new edges with positive residual capacity in the worst case both improved and unimproved algorithms will perform ( augmentationsif norman zadeh developed some examples on which this running time is based using his ideas we compose somewhat simpler network on which the algorithms have to perform ( augmentations and which is not dependent on choice of next path figure worst case example for the shortest augmenting path algorithm all vertexes except and are divided into four subsetss={ ,sk} ={ ,tk} ={ , pand ={ , pboth sets and contain nodes while both sets and contain nodes and are fixed integers each bold arc (connecting and thas unit capacity each dotted arc has an infinite capacity other arcs (which are solid and not straighthave capacity firstthe shortest augmenting path algorithm has to augment flow time along paths (ssttwhich have length equal to the capacities of these paths are unit after that the residual network will contain reversal arcs (tsand the algorithm will chose another augmenting paths (su tsv tof length then the algorithm will have to choose paths (su stv tof length and so on now let' calculate the parameters of our network the number of vertexes is the number of edges is pk as it easy to seethe number of augmentations is ( lovely professional university |
24,204 | notes consider that in this case and soone can verify that / in zadeh presents examples of networks that require / and / augmentationsbut these examples are dependent on choice of the shortest path we made worst-case tests with and vertexes and compared the running times of the improved version of the algorithm against the unimproved one as you can see on figure the improved algorithm is much faster on the network with nodes it works times faster practice analysis shows us thatin generalthe improved algorithm works / times faster figure -axis is the number of nodes -axis is working time in milliseconds blue colour indicates the shortest augmenting path algorithm and red does it improved version howeverour comparison in not definitivebecause we used only one kind of networks we just wanted to justify that the ( malgorithm works (ntimes faster than the (nm on dense network "network flow is an advanced branch of graph theory discuss network flow problem let (vebe directed network defined by set of vertexes (nodesand set of edges (arcsfor each edge (ije we associate capacity uij that denotes the maximum amount that can flow on the edge each edge (ije also has an associated cost cij that denotes the cost per unit flow on that edge we associate with each vertex number bi this value represents supply/demand of the vertex if bi node is supply nodeif bi node is demand node (its demand is equal to -biwe call vertex transshipment if bi is zero for simplificationlet' call transportation network and write (veucbin case we want to show all the network parameters explicitly lovely professional university |
24,205 | figure an example of the transportation network in this we have supply vertexes (with supply values and ) demand vertexes (with demand values and )and transshipment node each edge has two numberscapacity and costdivided by comma bi bj uij,cij notes - - - representing the flow on arc (ije by xijwe can obtain the optimization model for the minimum cost flow problemc ij xij minimize (xi subject to = ij : ij : <xij <uij for all vfor all (ije the first constraint states that the total outflow of node minus the total inflow of the node must be equal to mass balance (supply/demand valueof this node this is known as the mass balance constraints nextthe flow bound constraints model physical capacities or restrictions imposed on the flow' range as you can seethis optimization model describes typical relationship between warehouses and shopsfor examplein case where we have only one kind of product we need to satisfy the demand of each shop by transferring goods from the subset of warehouseswhile minimizing the expenses on transportation this problem could be solved using simplex-methodbut in this article we concentrate on some other ideas related to network flow theory before we move on to the three basic algorithms used to solve the minimum cost flow problemlet' review the necessary theoretical base finding solution when does the minimum cost flow problem have feasible (though not necessarily optimalsolutionhow do we determine whether it is possible to translate the goods or notif ddef siv bi then the problem has no solutionbecause either the supply or the demand dominates in the network and the mass balance constraints come into play lovely professional university |
24,206 | notes we can easily avoid this situationhoweverif we add special node with the supply/demand value br - now we have two optionsif (supply dominatesthen for each node with bi we add an arc (irwith infinite capacity and zero costotherwise (demand dominates)for each node with bi we add an arc (riwith the same properties now we have new network with siv{ }bi and it is easy to prove that this network has the same optimal value as the objective function consider the vertex as rubbish or scrap dump if the shops demand is less than what the warehouse suppliesthen we have to eject the useless goods as rubbish otherwisewe take the missing goods from the dump this would be considered shady in real lifeof coursebut for our purposes it is very convenient keep in mind thatin this casewe cannot say what exactly the "solutionof the corrected (with scrapproblem is and it is up to the reader how to classify the emergency uses of the "dump for examplewe can suggest that goods remain in the warehouses or some of the shop' demands remain unsatisfied even if we have we are not sure that the edge' capacities allow us to transfer enough flow from supply vertexes to demand ones to determine if the network has feasible flowwe want to find any transfer way what will satisfy all the problem' constraints of coursethis feasible solution is not necessarily optimalbut if it is absent we cannot solve the problem let us introduce source node and sink node for each node with bi we add source arc (sito with capacity bi and cost for each node with bi we add sink arc (itto with capacity -bi and cost figure maximum flow in the transformed network for simplicity we are ignoring the costs bi bj xij,uij - / / / - / / / / / / / / / - the new network is called transformed network nextwe solve maximum flow problem from to if the maximum flow saturates all the source and sink arcsthen the problem has feasible solutionotherwiseit is infeasible as for why this approach workswe'll leave its proof to the reader having found maximum flowwe can now remove sourcesinkand all adjacent arcs and obtain feasible flow in how do we detect whether the flow is optimal or notdoes this flow minimize costs of the objective function zwe usually verify "optimality conditionsfor the answer to these questionsbut let us put them on hold for moment and discuss some assumptions nowsuppose that we have network that has feasible solution does it have an optimal solutionif our network contains the negative cost cycle of infinite capacity then the objective lovely professional university |
24,207 | function will be unbounded howeverin some taskswe are able to assign finite capacity to each uncapacitated edge escaping such situation notes minimum spanning tree minimum spanning tree or minimum weight spanning tree is then spanning tree with weight less than or equal to the weight of every other spanning tree more generallyany undirected graph (not necessarily connectedhas minimum spanning forestwhich is union of minimum spanning trees for its connected components one example would be cable tv company laying cable to new neighborhood if it is constrained to bury the cable only along certain pathsthen there would be graph representing which points are connected by those paths some of those paths might be more expensivebecause they are longeror require the cable to be buried deeperthese paths would be represented by edges with larger weights spanning tree for that graph would be subset of those paths that has no cycles but still connects to every house there might be several spanning trees possible minimum spanning tree would be one with the lowest total cost figure minimum spanning tree graph minimum spanning tree tree for (total cost graph may have many spanning treesfor instance the complete graph on four vertices has sixteen spanning treesfigure complete graph with four vertices lovely professional university |
24,208 | notes figure sixteen spanning trees of complete graph on four vertices now suppose the edges of the graph have weights or lengths the weight of tree is just the sum of weights of its edges obviouslydifferent trees have different lengths the problemhow to find the minimum length spanning treethis problem can be solved by many different algorithms it is the topic of some very recent research there are several "bestalgorithmsdepending on the assumptions you makea randomized algorithm can solve it in linear expected time it can be solved in linear worst case time if the weights are small integers otherwisethe best solution is very close to linear but not exactly linear the exact bound is ( log beta( , )where the beta function has complicated definitionthe smallest such that log(log(loglog( ))is less than /nwhere the logs are nested times these algorithms are all quite complicatedand probably not that great in practice unless you're looking at really huge graphs here we'll go through two simple classical algorithms kruskal' algorithm we'll start with kruskal' algorithmwhich is easiest to understand and probably the best one for solving problems by hand kruskal' algorithm is an algorithm in graph theory that finds minimum spanning tree for connected weighted graph this means it finds subset of the edges that forms tree that includes every vertexwhere the total weight of all the edges in the tree is minimized if the graph is not connectedthen it finds minimum spanning forest ( minimum spanning tree for each connected componentkruskal' algorithm is an example of greedy algorithm this algorithm first appeared in proceedings of the american mathematical society in and was written by joseph kruskal lovely professional university |
24,209 | algorithm notes let (vewhich is represented by an adjacency list adj some support data structures is the forest - set of all (partialtrees mst is the minimum spanning treerepresented by set of edges is priority queue of edges kruskal( let be set of singleton set of all vertices in mst <{ < while not empty do (uv<extractmin( / is modified if find-set( !find-set(vthen /find-set(ireturns the set in /which vertex belongs to /this effectively does cycle check /if accepted begin merge(find-set( ),find-set( )in mst <mst union {(uv) end return mst proof of correctness let be connectedweighted graph and let be the subgraph of produced by the algorithm cannot have cyclesince the last edge added to that cycle would have been within one subtree and not between two different trees cannot be disconnectedsince the first encountered edge that joins two components of would have been added by the algorithm thusy is spanning tree of it remains to show that the spanning tree is minimallet be minimum spanning tree if then is minimum spanning tree otherwiselet be the first edge considered by the algorithm that is in but not in has cyclebecause you cannot add an edge to spanning tree and still have tree this cycle contains another edge which at the stage of the algorithm where is added to yhas not been considered this is because otherwise would not connect different trees but two branches of the same tree then / is also spanning tree its total weight is less than or equal to the total weight of this is because the algorithm visits before and therefore (eps (fif the weights are equalwe consider the next edge which is in but not in if there is no edge leftthe weight of is equal to the weight of although they consist of different edge set and is also minimum spanning tree lovely professional university |
24,210 | notes in the case where the weight of is less than the weight of we can conclude that is not minimum spanning treeand the assumption that there exist edges , with (ew(fis incorrect and therefore is minimum spanning tree (equal to or with different edge setbut with same weightfigure step by step representation of kruskal' algorithm ( ( ( ( ( extractmin ( )--accepted {{ }mst {( )( )( ( ) {( )( )} ( extractmin ( )-accepted {( }{ }mst {( )( )( ) {( )( )( ( )( extractmin ( )--rejected {{ }{ }mst {( )( )( ) {( )( )( ( extractmin (qaccepted {( )( )( ){ )mst {( ) {( )( )( )( )( )( ( extractmin ( )-accepted {( ){ }{ }mst {( )( ) {( )( )( )( ( {{ )( ){ }( )mst { {{ )( )( ){ ){ ){ ){ ( ( the algorithm continues until becomes emptybut since the forest has become one treeall remaining edges in will be rejected and no change will happen to mst lovely professional university |
24,211 | prim' algorithm notes prim' algorithm is an algorithm in graph theory that finds minimum spanning tree for connected weighted graph this means it finds subset of the edges that forms tree that includes every vertexwhere the total weight of all the edges in the tree is minimized the algorithm was discovered in by mathematician vojtich jarnik and later independently by computer scientist robert prim in and rediscovered by edsger dijkstra in therefore it is sometimes called the djp algorithmthe jarnik algorithmor the prim-jarnik algorithm figure diagrammatic representation of prim' algorithm algorithm let (vewhich is represented by an adjacency list adj some support data structures is an array of size |veach [icontains the shortest distance for vertex is priority queue of unknown vertices is an array of size |veach [icontains the parent of vertex is the source vertex prim(gs initialize [swith [swith and all other [ ( !=swith positive infinity and [ ( !=swith < /initialize with all vertices as unknown while not empty do begin <extractmin( / is modified mark as known /dequeing is the same as marking it as known for each vertex in adj[udo begin if is unknown and [vweight(uv)then do begin [vweight(uv/update with shorter weight [vu /update ' parent as lovely professional university |
24,212 | data structure is the logical or mathematical arrangement of data in memory it considers not only the physical layout of the data items in the memory but also the relationships between these data items and the operations that can be performed on these items the choice of appropriate data structures and algorithms forms the fundamental step in the design of an efficient program thusa thorough understanding of data structure concepts is essential for students who wish to work in the design and implementation of software systems ca general-purpose programming languagehaving gained popularity in both academia and industry serves as an excellent choice for learning data structures this second edition of data structures using has been developed to provide comprehensive and consistent coverage of both the abstract concepts of data structures as well as the implementation of these concepts using language the book utilizes systematic approach wherein the design of each of the data structures is followed by algorithms of different operations that can be performed on themand the analysis of these algorithms in terms of their running times new to the second edition based on the suggestions from students and faculty membersthis edition has been updated and revised to increase the clarity of presentation where required some of the prominent changes are as followsnew sections on omega and theta notationsmulti-linked listsforestsconversion of general trees into binary trees - treesbinary heap implementation of priority queuesinterpolation searchjump searchtree sortbucket hashingcylinder surface indexing additional programs on header linked listsparentheses checkingevaluation of prefix expressionspriority queuesmultiple queuestree sortfile handling address calculation sort new appendices on dynamic memory allocationgarbage collectionbacktrackingjohnson' problem stacks and queues and multi-way search trees are now covered in separate with more comprehensive explanation of concepts and applications extended material --this has been completely restructured and reorganized so that it now provides brief recapitulation of constructs and syntax functions and pointers which were included as independent in the first edition have now been jointly included in this --new sections on primitive and non-primitive data structuresdifferent approaches to designing algorithmsomegathetaand little notations have been included number of new examples have also been added which show how to find the complexity of different functions --this now includes brief sections on unionsa data type similar to structures --this has been expanded to include topics on multi-linked listsmulti-linked list implementation of sparse matricesand program on header linked lists www allitebooks com |
24,213 | preface to the second edition --new programs on parenthesis checking and evaluation of prefix expressions have been added recursionwhich is one of the most common applications of stackshas been moved to this --new programs on priority queues and multiple queues have been included --this now includes sections on general treesforestsconversion of general trees into binary treesand constructing binary tree from traversal results --an algorithm for in-order traversal of threaded binary tree has been added -- table summarizing the differences between and btrees and section on - trees have been included -- brief section on how binary heaps can be used to implement priority queues has been added --this now includes section which shows the adjacency multi-list representation of graphs --as result of organizationthe sections on linear and binary search have been moved from to this new search techniques such as interpolation searchjump searchand fibonacci search have also been included the also extends the concept of sorting by including sections on practical considerations for internal sortingsorting on multiple keysand tree sort --new sections on bucket hashing and rehashing have been included --this now includes section on cylinder surface indexing which is one of the widely used indexing structures for files stored in hard disks content and coverage this book is organized into introduction to provides review of basic constructs which helps readers to familiarize themselves with basic syntax and concepts that will be used to write programs in this book introduction to data strctures and algorithms introduces data structures and algorithms which serve as building blocks for creating efficient programs the explains how to calculate the time complexity which is key concept for evaluating the performance of algorithms from onwardsevery discusses individual data structures in detail arrays provides detailed explanation of arrays that includes one-dimensionaltwodimensionaland multi-dimensional arrays the operations that can be performed on such arrays are also explained strings discusses the concept of strings which are also known as character arrays the not only focuses on reading and writing strings but also explains various operations that can be used to manipulate the character arrays structures and unions deals with structures and unions structure is collection of related data items of different types which is used for implementing other data structures such as linked liststreesgraphsetc we will also read about unions which is also collection of variables of different data typesexcept that in case of unionswe can only store information in one field at any one time linked lists discusses different types of linked lists such as singly linked listsdoubly linked listscircular linked listsdoubly circular linked listsheader linked listsand multi-linked lists linked list is preferred data structure when it is required to allocate memory dynamically www allitebooks com |
24,214 | stacks focuses on the concept of last-infirst-out (lifodata structure called stacks the also shows the practical implementation of these data structures using arrays as well as linked lists it also shows how stacks can be used for the evaluation of arithmetic expressions queues deals with the concept of first-infirst-out (fifodata structure called queues the also provides the real-world applications of queues trees focuses on binary treestheir traversal schemes and representation in memory the also discusses expression treestournament treesand huffman treesall of which are variants of simple binary trees ,efficient binary trees broadens the discussion on trees taken up in by going one step ahead and discussing efficient binary trees the discusses binary search treesthreaded binary treesavl treesred-black treesand splay trees multi-way search trees explores trees which can have more than one key value in single nodesuch as -way search treesb treesbtreestriesand - trees heaps discusses three types of heaps--binary heapsbinomial heapsand fibonacci heaps the not only explains the operations on these data structures but also makes comparisonthereby highlighting the key features of each structure graphs contains detailed explanation of non-linear data structure called graphs it discusses the memory representationtraversal schemesand applications of graphs in the real world searching and sorting covers two of the most common operations in computer sciencei searching and sorting list of values it gives the techniquecomplexityand program for different searching and sorting techniques hashing and collision deals with different methods of hashing and techniques to resolve collisions the last of the bookfiles and their organizationdiscusses the concept related to file organization it explains the different ways in which files can be organized on the hard disk and the indexing techniques that can be used for fast retrieval of data the book also provides set of seven appendices appendix introduces the concept of dynamic memory allocation in programs appendix provides brief discussion of garbage collection technique which is used for automatic memory management appendix explains backtracking which is recursive algorithm that uses stacks appendix discusses johnson' algorithm which is used in applications where an optimal order of execution of different activities has to be determined appendix includes two programs which show how to read and write binary files appendix includes program which shows how to sort list of numbers using address calculation sort appendix provides wise answers to all the objective questions reema thareja www allitebooks com |
24,215 | preface to the second edition preface to the first edition viii introduction to introduction to data structures and algorithms arrays strings structures and unions linked lists stacks queues trees efficient binary trees multi-way search trees heaps graphs searching and sorting hashing and collision files and their organization appendix amemory allocation in programs appendix bgarbage collection appendix cbacktracking appendix djosephus problem appendix efile handling in appendix faddress calculation sort appendix ganswers index www allitebooks com |
24,216 | detailed contents preface to the second edition preface to the first edition viii introduction to introduction identifiers and keywords basic data types variables and constants writing the first program input and output functions operators and expressions type conversion and typecasting control statements decision control statements iterative statements break and continue statements functions why are functions needed using functions passing parameters to functions pointers declaring pointer variables pointer expressions and pointer arithmetic null pointers generic pointers pointer to pointers drawback of pointers introduction to data structures and algorithms basic terminology elementary data structure organization classification of data structures operations on data structures abstract data type algorithms different approaches to designing an algorithm control structures used in algorithms time and space complexity worst-caseaverage-casebest-caseand amortized time complexity time-space trade-off expressing time and space complexity algorithm efficiency big notation omega notation ( theta notation ( other useful notations arrays introduction declaration of arrays accessing the elements of an array calculating the address of array elements calculating the length of an array storing values in arrays operations on arrays traversing an array www allitebooks com |
24,217 | inserting an element in an array deleting an element from an array merging two arrays passing arrays to functions passing individual elements passing the entire array pointers and arrays arrays of pointers two-dimensional arrays declaring two-dimensional arrays initializing two-dimensional arrays accessing the elements of two-dimensional arrays operations on two-dimensional arrays passing two-dimensional arrays to functions pointers and two-dimensional arrays multi-dimensional arrays pointers and three-dimensional arrays sparse matrices applications of arrays strings introduction reading strings writing strings operations on strings arrays of strings pointers and strings structures and unions introduction structure declaration typedef declarations initialization of structures accessing the members of structure copying and comparing structures nested structures arrays of structures structures and functions passing individual members passing the entire structure passing structures through pointers self-referential structures unions declaring union accessing member of union initializing unions arrays of union variables unions inside structures linked lists introduction basic terminologies linked lists versus arrays memory allocation and de-allocation for linked list singly linked lists traversing linked list searching for value in linked list inserting new node in linked list deleting node from linked list circular linked lists inserting new node in circular linked list deleting node from circular linked list doubly linked lists inserting new node in doubly linked list |
24,218 | deleting node from doubly linked list circular doubly linked lists inserting new node in circular doubly linked list deleting node from circular doubly linked list header linked lists multi-linked lists applications of linked lists polynomial representation stacks introduction to stacks array representation of stacks operations on stack push operation pop operation peek operation linked representation of stacks operations on linked stack push operation pop operation multiple stacks applications of stacks reversing list implementing parentheses checker evaluation of arithmetic expressions recursion queues introduction to queues array representation of queues linked representation of queues types of queues circular queues deques priority queues multiple queues applications of queues trees introduction basic terminology types of trees general trees forests binary trees binary search trees expression trees tournament trees creating binary tree from general tree traversing binary tree pre-order traversal in-order traversal post-order traversal level-order traversal constructing binary tree from traversal results huffman' tree applications of trees efficient binary trees binary search trees operations on binary search trees searching for node in binary search tree inserting new node in binary search tree deleting node from binary search tree determining the height of binary search tree determining the number of nodes finding the mirror image of binary search tree finding the smallest node in binary search tree finding the largest node in binary search tree threaded binary trees traversing threaded binary tree |
24,219 | avl trees operations on avl trees searching for node in an avl tree red-black trees properties of red-black trees operations on red-black trees applications of red-black trees splay trees operations on splay trees advantages and disadvantages of splay trees multi-way search trees introduction to -way search trees trees searching for an element in tree inserting new element in tree deleting an element from tree applications of trees btrees inserting new element in btree deleting an element from btree - trees searching for an element in - tree inserting new element in - tree deleting an element from - tree trie heaps binary heaps inserting new element in binary heap deleting an element from binary heap applications of binary heaps binomial heaps linked representation of binomial heaps operations on binomial heaps fibonacci heaps structure of fibonacci heaps operations on fibonacci heaps comparison of binarybinomialand fibonacci heaps applications of heaps graphs introduction graph terminology directed graphs terminology of directed graph transitive closure of directed graph bi-connected components representation of graphs adjacency matrix representation adjacency list representation adjacency multi-list representation graph traversal algorithms breadth-first search algorithm depth-first search algorithm topological sorting shortest path algorithms minimum spanning trees prim' algorithm kruskal' algorithm dijkstra' algorithm warshall' algorithm |
24,220 | modified warshall' algorithm applications of graphs searching and sorting introduction to searching linear search binary search interpolation search jump search introduction to sorting sorting on multiple keys practical considerations for internal sorting bubble sort insertion sort selection sort merge sort quick sort radix sort heap sort shell sort tree sort comparison of sorting algorithms external sorting hashing and collision introduction hash tables hash functions different hash functions division method appendix amemory allocation in programs appendix bgarbage collection appendix cbacktracking appendix djosephus problem appendix efile handling in appendix faddress calculation sort appendix ganswers index multiplication method mid-square method folding method collisions collision resolution by open addressing collision resolution by chaining pros and cons of hashing applications of hashing real world applications of hashing files and their organization introduction data hierarchy file attributes text and binary files basic file operations file organization sequential organization relative file organization indexed sequential file organization indexing ordered indices dense and sparse indices cylinder surface indexing multi-level indices inverted indices -tree indices hashed indices |
24,221 | introduction to learning objective this book deals with the study of data structures through before going into detailed analysis of data structuresit would be useful to familiarize ourselves with the basic knowledge of programming in thereforein this we will learn about the various constructs of such as identifiers and keywordsdata typesconstantsvariablesinput and output functionsoperatorscontrol statementsfunctionsand pointers introduction the programming language 'cwas developed in the early by dennis ritchie at bell laboratories although was initially developed for writing system softwaretoday it has become such popular language that variety of software programs are written using this language the greatest advantage of using for programming is that it can be easily used on different types of computers many other programming languages such as +and java are also based on which means that you will be able to learn them easily in the future todayc is widely used with the unix operating system structure of program program contains one or more functionswhere function is defined as group of statements that perform well-defined task figure shows the structure of program the statements in function are written in logical sequence to perform specific task the main(function is the most important function and is part of every program ratherthe execution of program begins with this function from the structure given in fig we can conclude that program can have any number of functions depending on the tasks that have to be performedand each function can have any number |
24,222 | data structures using main(statement statement statement nfunction (statement statement statement nfunction (statement statement statement nfunctionn(statement statement statement nfigure structure of program of statements arranged according to specific meaningful sequence note that programmers can choose any name for functions it is not mandatory to write function function etc with an exception that every program must contain one function that has its name as main( identifiers and keywords every word in program is either an identifier or keyword identifiers identifiers are basically names given to program elements such as variablesarraysand functions they are formed by using sequence of letters (both uppercase and lowercase)numeralsand underscores following are the rules for forming identifier namesidentifiers cannot include any special characters or punctuation marks (like #$^?etc except the underscore "_there cannot be two successive underscores keywords cannot be used as identifiers the case of alphabetic characters that form the identifier name is significant for example'firstis different from 'firstand 'firstidentifiers must begin with letter or an underscore howeveruse of underscore as the first character must be avoided because several complier-defined identifiers in the standard library have underscore as their first character soinadvertently duplicated names may cause definition conflicts identifiers can be of any reasonable length they should not contain more than characters (they can actually be longer than but the compiler looks at only the first characters of the name keywords like every computer languagec has set of reserved words often known as keywords that cannot be used as an identifier all keywords are basically sequence of characters that have fixed meaning by conventionall keywords must be written in lower case letters table contains the list of keywords in table keywords in language auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while basic data types data type determines the set of values that data item can take and the operations that can be performed on the item language provides four basic data types table lists the data typestheir sizerangeand usage for programmer the char data type is of one byte and is used to store single characters note that does not provide any data type for storing text this is because text is made up of individual characters you |
24,223 | might have been surprised to see that the range of char is given as - to char is supposed to store characters not numbersso why this rangethe answer is that in the memorycharacters are stored in their ascii codes for examplethe character 'ahas the ascii code of in memory we will not store 'abut (in binary number formattable basic data types in data type size in bytes range use char - to to store characters int - to to store integer numbers float - to + to store floating point numbers double - to + to store big floating point numbers in additionc also supports four modifiers--two sign specifiers (signed and unsignedand two size specifiers (short and longtable shows the variants of basic data types table basic data types and their variants data type size in bytes range char - to unsigned char to signed char - to int - to unsigned int to signed int - to short int - to unsigned short int to signed short int - to long int - to unsigned long int to - to signed long int float - to + double - to + long double - to + note when the basic data type is omitted from declarationthen automatically type int is assumed for examplelong var//int is implied while the smaller data types take less memorythe larger data types incur performance penalty although the data type we use for our variables does not have big impact on the speed or memory usage of the applicationwe should always try to use int unless there is need to use any other data type variables and constants variable is defined as meaningful name given to data storage location in the computer memory when using variablewe actually refer to the address of the memory where the data is stored language supports two basic kinds of variables |
24,224 | data structures using numeric variables numeric variables can be used to store either integer values or floating point values modifiers like shortlongsignedand unsigned can also be used with numeric variables the difference between signed and unsigned numeric variables is that signed variables can be either negative or positive but unsigned variables can only be positive thereforeby using an unsigned variable we can increase the maximum positive range when we omit the signed/unsigned modifierc language automatically makes it signed variable to declare an unsigned variablethe unsigned modifier must be explicitly added during the declaration of the variable character variables character variables are just single characters enclosed within single quotes these characters could be any character from the ascii character set--letters (' '' ')numerals (' ')or special characters ('&'declaring variables to declare variablespecify the data type of the variable followed by its name the data type indicates the kind of values that the variable can store variable names should always be meaningful and must reflect the purpose of their usage in the program in cvariable declaration always ends with semi-colon for exampleint emp_numfloat salarychar gradedouble balance_amountunsigned short int acc_noin cvariables can be declared at any place in the program but two things must be kept in mind firstvariables should be declared before using them secondvariables should be declared closest to their first point of use so that the source code is easier to maintain initializing variables while declaring the variableswe can also initialize them with some value for exampleint emp_num float salary char grade ' 'double balance_amount constants constants are identifiers whose values do not change while values of variables can be changed at any timevalues of constants can never be changed constants are used to define fixed values like pi or the charge on an electron so that their value does not get changed in the program even by mistake declaring constants to declare constantprecede the normal variable declaration with const keyword and assign it value const float pi |
24,225 | writing the first program to write programwe first need to write the code for thatopen text editor if you are windows useryou may use notepad and if you prefer working on unix/linuxyou can use emac or vi once the text editor is opened on your screentype the following statements#include int main(printf("\ welcome to the world of ");/prints the message on the screen return ;/returns value to the operating system after writing the codeselect the directory of your choice and save the file as first #include this is the first statement in our code that includes file called stdio this file has some in-built functions by simply including this file in our codewe can use these functions directly stdio basically stands for standard input/outputwhich means it has functions for input and output of data like reading values from the keyboard and printing the results on the screen every program contains main(function which is the starting point of the program int is the return value of the main function after all the statements in the program have been executedthe last statement of the program will return an integer value to the operating system the concepts will be clear to us when we read this in toto so even if you do not understand certain thingsdo not worry int main(table the two curly brackets are used to group all the related statements of the main function escape sequence purpose \ audible signal \ backspace \ tab \ new line \ vertical tab \ new page\clear screen \ carriage return note the printf function is defined in the stdio file and is used to print text on the screen the message that has to be displayed on the screen is enclosed within double quotes and put inside brackets printf("\ welcome to the world of ")escape sequences \ is an escape sequence and represents newline character it is used to print the message on new line on the screen other escape sequences supported by language are shown in table this is return command that is used to return value to the operating system to give an indication that there were no errors during the execution of the program return every statement in the main function ends with semi-colon (;if you are windows userthen open the command prompt by clicking startaerun and typing "commandand clicking ok using the command promptchange to the directory in which you saved your file and then typefirst :\>tc first in case you are working on unix/linux operating systemthen exit the text editor and type $cc first -ofirst the - is for the output file name if you leave out the -othen the file name out is used |
24,226 | data structures using this command is used to compile your program if there are any mistakes in the programthen the compiler will tell you what mistake(syou have made and on which line the error has occurred in case of errorsyou need to re-open your file and correct the mistakes howeverif everything is rightthen no error(swill be reported and the compiler will create an exe file for your program this exe file can be directly run by typing "first exefor windows and /firstfor unix/linux operating system when you run the exe filethe output of the program will be displayed on screen that iswelcome to the world of note the printf and return statements have been indented or moved away from the left side this is done to make the code more readable using comments comments are way of explaining what program does supports two types of comments /is used to comment single statement /is used to comment multiple statements /is ended with *and all statements that lie between these characters are commented note that comment statements are not executed by the compiler ratherthey are ignored by the compiler as they are simply added in programs to make the code understandable by programmers as well as other users it is good habit to always put comment at the top of program that tells you what the program does this helps in defining the usage of the program the moment you open it standard header files till now we have used printf(functionwhich is defined in the stdio header file even in other programs that we will be writingwe will use many functions that are not written by us for exampleto use the strcmp(function that compares two stringswe will pass string arguments and retrieve the result we do not know the details of how these functions work such functions that are provided by all compilers are included in standard header files examples of these standard header files includestring for string handling functions stdlib for some miscellaneous functions stdio for standardized input and output functions math for mathematical functions alloc for dynamic memory allocation conio for clearing the screen all the header files are referenced at the start of the source code file that uses one or more functions from these files input and output functions the most fundamental operation in program is to accept input values from standard input device and output the data produced by the program to standard output device as shown in section we can assign values to variables using the assignment operator '=for exampleint what if we want to assign value to variable that is inputted from the user at run-timethis is done by using the scanf function that reads data from the keyboard similarlyfor outputting results of |
24,227 | the programprintf function is used that sends results to terminal like printf and scanfthere are different functions in that can carry out the input-output operations these functions are collectively known as standard input/output library program that uses standard input/output functions must contain the following statement at the beginning of the program#include scanf(the scanf()function is used to read formatted data from the keyboard the syntax of the scanf(function can be given asscanf ("control string"arg arg arg argn)the control string specifies the type and format of the data that has to be obtained from the keyboard and stored in the memory locations pointed by the argumentsarg arg ,argn the prototype of the control string can be given as%[*][width][modifier]type is an optional argument that suppresses assignment of the input field that isit indicates that data should be read from the stream but ignored (not stored in the memory locationwidth is an optional argument that specifies the maximum number of characters to be read howeverif the scanf function encounters white space or an unconvertible characterinput is terminated modifier is an optional argument (hlor lwhich modifies the type specifier modifier is used for short int or unsigned short intl is used for long intunsigned long intor double values finallyl is used for long double data values type specifies the type of data that has to be read it also indicates how this data is expected to be read from the user the type specifiers for scanf function are given in table table type specifiers type % % % % ,% ,% ,% ,% qualifying input for single characters for integer values for floating point numbers % for octal numbers % for sequence of (string ofcharacters % for unsigned integer values % ,% for hexadecimal values the scanf function ignores any blank spacestabsand newlines entered by the user the function simply returns the number of input fields successfully scanned and stored as we have not studied functions till nowunderstanding scanf function in depth will be bit difficult herebut for now just understand that the scanf function is used to store values in memory locations associated with variables for thisthe function should have the address of the variables the address of the variable is denoted by an sign followed by the name of the variable look at the following code that shows how we can input value in variable of int data typeint numscanf(% "&num)the scanf function reads first four digits into the address or the memory location pointed by num |
24,228 | data structures using note in case of reading stringswe do not use the sign in the scanf function printf(the printf function is used to display information required by the user and also prints the values of the variables its syntax can be given asprintf ("control string"arg ,arg ,arg ,argn)after the control stringthe function can have as many arguments as specified in the control string the control string contains format specifiers which are arranged in the order so that they correspond with the arguments in the variable list it may also contain text to be printed such as instructions to the useridentifier namesor any other text to make the text readable note that there must be enough arguments because if there are not enough argumentsthen the result will be completely unpredictable howeverif by mistake you specify more number of argumentsthe excess arguments will simply be ignored the prototype of the control string can be given as below%[flags][width]precision][modifier]type each control string must begin with sign flags is an optional argumentwhich specifies output justification like decimal pointnumerical signtrailing zeros or octadecimal or hexadecimal prefixes table shows different types of flags with their descriptions table flags in printf(flags description left-justify within the given field width displays the data with its numeric sign (either or -used to provide additional specifiers like oxx xor for octal and hexadecimal values respectively for values different than zero the number is left-padded with zeroes ( instead of spaces width is an optional argument which specifies the minimum number of positions that the output characters will occupy if the number of output characters is smaller than the specified widththen the output would be right justified with blank spaces to the left howeverif the number of characters is greater than the specified widththen all the characters would be printed precision is an optional argument which specifies the number of digits to print after the decimal point or the number of characters to print from string modifier field is same as given for scanf(function type is used to define the type and the interpretation of the value of the corresponding argument the type specifiers for printf function are given in table the most simple printf statement is printf ("welcome to the world of language")the function when executed prompts the message enclosed in the quotation to be displayed on the screen for float the following examples show output under different format specificationsprintf ("% "xprintf("% " ) |
24,229 | printf("% " )printf("% " ) operators and expressions language supports different types of operatorswhich can be used with variables and constants to form expressions these operators can be categorized into the following major groupsarithmetic operators relational operators equality operators logical operators unary operators conditional operator bitwise operators assignment operators comma operator sizeof operator we will now discuss all these operators arithmetic operators consider three variables declared asint = = resultwe will use these variables to explain arithmetic operators table shows the arithmetic operatorstheir syntaxand usage in language table arithmetic operators operation operator syntax comment result multiply result divide result addition result subtraction result modulus result in table and (on which the operator is appliedare called operands arithmetic operators can be applied to any integer or floating point number the additionsubtractionmultiplicationand division (+-*and /operators are the usual arithmetic operatorsso you are already familiar with these operators howeverthe operator might be new to you the modulus operator (%finds the remainder of an integer division this operator can be applied only on integer operands and cannot be used on float or double operands while performing modulo divisionthe sign of the result is always the sign of the first operand (the dividendtherefore - - - - - - when both operands of the division operator (/are integersthe division is performed as an integer division integer division always results in an integer result sothe result is always rounded-off by ignoring the remainder therefore / and - / - |
24,230 | data structures using note it is not possible to divide any number by zero this is an illegal operation that results in run-time division-by-zero exception thereby terminating the program except for modulus operatorall other arithmetic operators can accept mix of integer and floating point numbers if both operands are integersthe result will be an integerif one or both operands are floating point numbers then the result would be floating point number all the arithmetic operators bind from left to right multiplicationdivisionand modulus operators have higher precedence over addition and subtraction operators thusif an arithmetic expression consists of mix of operatorsthen multiplicationdivisionand modulus will be carried out first in left to right orderbefore any addition and subtraction can be performed for example relational operators relational operatoralso known as comparison operatoris an operator that compares two values or expressions relational operators return true or false valuedepending on whether the conditional relationship between the two operands holds or not table relational operators for exampleto test if is less than operator meaning example relational operator is used as this expression will return true value if is less than less than gives yotherwise the value of the expression will greater than gives be false provides four relational operators <less than or equal to < gives which are illustrated in table these >greater than equal to >= gives operators are evaluated from left to right equality operators language also supports two equality operators to compare operands for strict equality or inequality they are equal to (==and not equal to (!=operators the equality operators have lower precedence than the relational operators table equality operators the equal-to operator (==returns true ( if operands operator meaning on both sides of the operator have the same valueotherwiseit returns false ( on the contrarythe not=returns if both operands are equal otherwise equal-to operator (!=returns true ( if the operands do !returns if operands do not not have the same valueelse it returns false ( table have the same value otherwise summarizes equality operators logical operators language supports three logical operators they are logical and (&&)logical or (||)and logical not (!as in case of arithmetic expressionslogical expressions are evaluated from left to right table truth table of logical and & logical and (&&logical and is binary operatorwhich simultaneously evaluates two values or relational expressions if both the operands are truethen the whole expression is true if both or one of the operands is falsethen the whole expression evaluates to false the truth table of logical and operator is given in table |
24,231 | for example( cthe whole expression is true only if both expressions are truei if is greater than and table truth table of logical or | table truth table of logical not logical or (||logical or returns false value if both the operands are false otherwise it returns true value the truth table of logical or operator is given in table for example( cthe whole expression is true if either is greater than or is greater than or is greater than both and logical not (!the logical not operator takes single expression and produces zero if the expression evaluates to non-zero value and produces if the expression produces zero the truth table of logical not operator is given in table for exampleint bb !anow the value of this is because value of ! the value of ! is assigned to bhence the result unary operators unary operators act on single operands language supports three unary operators they are unary minusincrementand decrement operators unary minus (-unary minus operator negates the value of its operand for exampleif number is positive then it becomes negative when preceded with unary minus operator similarlyif the number is negativeit becomes positive after applying the unary minus operator for exampleint ab -( )the result of this expression is - because variable has positive value after applying unary minus operator (-on the operand bthe value becomes - which indicates it has negative value increment operator (++and decrement operator (-the increment operator is unary operator that increases the value of its operand by similarlythe decrement operator decreases the value of its operand by for example- is equivalent to writing the increment/decrement operators have two variantsprefix and postfix in prefix expression (++ or - )the operator is applied before the operand while in postfix expression ( +or --)the operator is applied after the operand an important point to note about unary increment and decrement operators is that ++ is not same as +similarly- is not the same as xalthoughx+and ++ both increment the value of by in the former casethe value of is returned before it is incremented whereas in the latter casethe value of is returned after it is incremented for example |
24,232 | data structures using int yy ++is equivalent to writing xx whereas ++xis equivalent to writing xthe same principle applies to unary decrement operators note that unary operators have higher precedence than the binary operators and if in an expression we have more than one unary operator then they are evaluated from right to left conditional operator the syntax of the conditional operator is exp exp exp exp is evaluated first if it is truethen exp is evaluated and becomes the result of the expressionotherwise exp is evaluated and becomes the result of the expression for examplelarge ( ba the conditional operator is used to find the larger of two given numbers first exp that is bis evaluated if is greater than bthen large aelse large hencelarge is equal to either or bbut not both conditional operators make the program code more compactmore readableand safer to use as it is easier to both check and guarantee the arguments that are used for evaluation conditional operator is also known as ternary operator as it takes three operands bitwise operators as the name suggestsbitwise operators perform operations at the bit level these operators includebitwise andbitwise orbitwise xorand shift operators bitwise and like boolean and (&&)bitwise and operator (&performs operation on bits instead of bytescharsintegersetc when we use the bitwise and operatorthe bit in the first operand is anded with the corresponding bit in the second operand the truth table is the same as we had seen in logical and operation the bitwise and operator compares each bit of its first operand with the corresponding bit of its second operand if both bits are the corresponding bit in the result is and otherwise for example bitwise or when we use the bitwise or operator (|)the bit in the first operand is ored with the corresponding bit in the second operand the truth table is the same as we had seen in logical or operation the bitwise or operator compares each bit of its first operand with the corresponding bit of its second operand if one or both bits are the corresponding bit in the result is and otherwise for example bitwise xor when we use the bitwise xor operatorthe bit in the first operand is xored with the corresponding |
24,233 | table truth table of bitwise xor bit in the second operand the truth table of bitwise xor operator is shown in table the bitwise xor operator compares each bit of its first operand with the corresponding bit of its second operand if one of the bits is the corresponding bit in the result is and otherwise for example bitwise not (~the bitwise not or complement is unary operator that performs logical negation on each bit of the operand by performing negation of each bitit actually produces the one' complement of the given binary value bitwise not operator sets the bit to if it was initially and sets it to if it was initially for example ~ shift operators supports two bitwise shift operators they are shift left (>the syntax for shift operation can be given as operand op num where the bits in the operand are shifted left or right depending on the operator (leftif the operator is >by number of places denoted by num for exampleif we have then < produces when we apply left shiftevery bit in is shifted to the left by one place sothe msb (most significant bitof is lostthe lsb (least significant bitof is set to thereforeif we have then < gives result on the contrarywhen we apply right shiftevery bit in is shifted to the right by one place sothe lsb of is lostthe msb of is set to for exampleif we have then > gives result similarlyif we have then > gives result note the expression is equivalent to division of by if is unsigned or has non-negative value assignment operators in languagethe assignment operator is responsible for assigning values to the variables while the equal sign (=is the fundamental assignment operatorc also supports other assignment operators that provide shorthand ways to represent common variable assignments when an equal sign is encountered in an expressionthe compiler processes the statement on the right side of the sign and assigns the result to the variable on the left side for exampleint xx assigns the value to variable the assignment operator has right-to-left associativityso the expression |
24,234 | data structures using table assignment operators operator example /float = float = / \int int \ *int int * +int int + -int int - &int int & ^int int ^ <<int int << >>int int >>ba is evaluated as ( ( ( )))first is assigned to cthen the value of is assigned to finallythe value of is assigned to table contains list of other assignment operators that are supported by comma operator the comma operatorwhich is also called the sequential-evaluation operatortakes two operands it works by evaluating the first expression and discarding its valueand then evaluates the second expression and returns the value as the result of the expression comma-separated expressions when chained together are evaluated in left-to-right sequence with the right-most value yielding the result of the expression among all the operatorsthe comma operator has the lowest precedence thereforewhen comma operator is usedthe entire expression evaluates to the value of the right expression for examplethe following statement first increments athen increments band then assigns the value of to int = = = (++ab+= )nowthe value of sizeof operator sizeof is unary operator used to calculate the size of data types this operator can be applied to all data types when using this operatorthe keyword sizeof is followed by type namevariableor expression the operator returns the size of the data typevariableor expression in bytes that isthe sizeof operator is used to determine the amount of memory space that the data type/variable/expression will take when type name is usedit is enclosed in parenthesesbut in case of variable names and expressionsthey can be specified with or without parentheses sizeof expression returns an unsigned value that specifies the size of the space in bytes required by the data typevariableor expression for examplesizeof(charreturns that is the size of character data type if we haveint unsigned int resultresult sizeof( )then result that isspace required to store the variable in memory since is an integerit requires bytes of storage space operator precedence chart table lists the operators that language supports in the order of their precedence (highest to lowestthe associativity indicates the order in which the operators of equal precedence in an expression are evaluated |
24,235 | table operators precedence chart operator associativity (left-to-right [--++(postfixright-to-left --(postfix++(prefixright-to-left --(prefix+(unary(unary(type*(indirection&(addresssizeof left-to-right left-to-right left-to-right <left-to-right >=!left-to-right left-to-right left-to-right left-to-right &left-to-right |left-to-right ?right-to-left right-to-left +-*/%&^|>,(commaleft-to-right examples of expressions using the precedence chart if we have the following variable declarationsint - float then( ( ( ( ( ( ( (ha & & | |(! || & | (( & |( ( & |( /- & (( )& ( & & ! |! | ((! |(! )|( ( | | | (( ( )| ( |- ( ! | +(( (! )|( ++( | programming example write program to calculate the area of circle #include #include int main(float radiusdouble areaclrscr()printf("\ enter the radius of the circle ")scanf("% "&radius)area radius radiusprintf(\ area lf"area)return output enter the radius of the circle area |
24,236 | data structures using type conversion and typecasting type conversion or typecasting of variables refers to changing variable of one data type into another while type conversion is done implicitlycasting has to be done explicitly by the programmer we will discuss both these concepts here type conversion type conversion is done when the expression has variables of different data types so to evaluate the expressionthe data type is promoted from lower to higher level where the hierarchy of data types can be given asdoublefloatlongintshortand char for exampletype conversion is automatically done when we assign an integer value to floating point variable consider the following codefloat xint ynowx as integer value is automatically converted into its equivalent floating point representation typecasting typecasting is also known as forced conversion it is done when the value of one data type has to be converted into the value of another data type the code to perform typecasting can be given asfloat salary int salsal (intsalarywhen floating point numbers are converted to integersthe digits after the decimal are truncated thereforedata is lost when floating point representations are converted to integral representations as we can see in the codetypecasting can be done by placing the destination data type in parentheses followed by the variable name that has to be converted hencewe conclude that typecasting is done to make variable of one data type to act like variable of another type programming example write program to convert an integer into the corresponding floating point number #include #include int main(float f_numint i_numclrscr()printf("\ enter any integer")scanf("% "&i_num)f_num (float)i_numprintf("\ the floating point variant of % is % "i_numf_num)return output enter any integer the floating point variant of is www allitebooks com |
24,237 | control statements till now we know that the code in the program is executed sequentially from the first line of the program to its last line that isthe second statement is executed after the firstthe third statement is executed after the secondso on and so forth although this is truein some cases we want only selected statements to be executed control flow statements enable programmers to conditionally execute particular block of code there are three types of control statementsdecision control (branching)iterative (looping)and jump statements while branching means deciding what actions have to be takenloopingon the other handdecides how many times the action has to be taken jump statements transfer control from one point to another point decision control statements supports decision control statements that can alter the flow of sequence of instructions these statements help to jump from one part of the program to another depending on whether particular condition is satisfied or not these decision control statements include(aif statement(bif-else statement(dswitch-case statement (cif-else-if statementand if statement if statement is the simplest decision control statement that is frequently used in decision making the general form of simple if statement is shown in fig syntax of if statement if (test expressionstatement statement nstatement xtest expression false true statement block statement figure if statement construct the if block may include statement or statements enclosed within curly brackets first the test expression is evaluated if the test expression is truethe statements of the if block are executedotherwise these statements will be skipped and the execution will jump to statement the statement in an if block is any valid language statementand the test expression is any valid language expression that evaluates to either true or false in addition to simple relational expressionswe can also use compound expressions formed using logical operators note that there is no semi-colon after the test expression this is because the condition and statement should be put together as single statement |
24,238 | data structures using #include int main(int = if ( > ++printf("\ % " )return in the above codewe take variable and initialize it to in the test expressionwe check if the value of is greater than as the test expression evaluates to trueand the value of is incremented after thatthe value of is printed on the screen the output of this program is observe that the printf statement will be executed even if the test expression is false note in case the statement block contains only one statementputting curly brackets becomes optional if there are more than one statement in the statement blockputting curly brackets becomes mandatory if-else statement we have studied that using if statement plays vital role in conditional branching its usage is very simple the test expression is evaluatedif the result is truethe statement(sfollowed by the expression is executedelse if the expression is falsethe statement is skipped by the compiler what if you want separate set of statements to be executed if the expression returns false valuein such caseswe can use an if-else statement rather than using simple if statement the general form of simple if-else statement is shown in fig syntax of if-else statement if (test expressionstatement block else statement block statement xtrue test expression statement block false statement block statement figure if-else statement construct in the if-else constructfirst the test expression is evaluated if the expression is truestatement block is executed and statement block is skipped otherwiseif the expression is falsestatement block is executed and statement block is ignored in any case after the statement block or gets executedthe control will pass to statement thereforestatement is executed in every case |
24,239 | programming example write program to find whether number is even or odd #include int main(int aprintf("\ enter the value of ")scanf("% "& )if( % == printf("\ % is even" )else printf("\ % is odd" )return output enter the value of is even if-else-if statement language supports if-else-if statements to test additional conditions apart from the initial test expression the if-else-if construct works in the same way as normal if statement its construct is given in fig syntax of if-else-if statement if (test expression statement block else if (test expression statement block else statement block xstatement ytrue test expression statement block true false test expression statement block false statement block statement figure if-else-if statement construct note that it is not necessary that every if statement should have an else block as supports simple if statements after the first test expression or the first if branchthe programmer can have as many else-if branches as he wants depending on the expressions that have to be tested for examplethe following code tests whether number entered by the user is negativepositiveor equal to zero #include int main( |
24,240 | data structures using int numprintf("\ enter any number ")scanf("% "&num)if(num== printf("\ the value is equal to zero")else if(num> printf("\ the number is positive")else printf("\ the number is negative")return note that if the first test expression evaluates to true valuei num= then the rest of the statements in the code will be ignored and after executing the printf statement that displays 'the value is equal to zero'the control will jump to return statement switch-case statement switch-case statement is multi-way decision statement that is simplified version of an ifelse-if block the general form of switch statement is shown in fig true value syntax of switch statement statement block switch (variablecase value statement block breakcase value statement block breakcase value nstatement block nbreakdefaultstatement block dbreakstatement xtrue statement block false value false false true value statement block false statement block statement figure switch-case statement construct the power of nested if-else-if statements lies in the fact that it can evaluate more than one expression in single logical structure switch statements are mostly used in two situationswhen there is only one variable to evaluate in the expression when many conditions are being tested for |
24,241 | when there are many conditions to testusing the if and else-if constructs becomes complicated and confusing thereforeswitch case statements are often used as an alternative to long if statements that compare variable to several 'integralvalues (integral values are those values that can be expressed as an integersuch as the value of charswitch statements are also used to handle the input given by the user we have already seen the syntax of the switch statement the switch case statement compares the value of the variable given in the switch statement with the value of each case statement that follows when the value of the switch and the case statement matchesthe statement block of that particular case is executed did you notice the keyword default in the syntax of the switch case statementdefault is the case that is executed when the value of the variable does not match with any of the values of the case statements that isdefault case is executed when no match is found between the values of switch and case statements and thus there are no statements to be executed although the default case is optionalit is always recommended to include it as it handles any unexpected case in the syntax of the switch-case statementwe have used another keyword break the break statement must be used at the end of each case because if it is not usedthen the case that matched and all the following cases will be executed for exampleif the value of switch statement matched with that of case then all the statements in case as well as the rest of the cases including default will be executed the break statement tells the compiler to jump out of the switch case statement and execute the statement following the switch-case construct thusthe keyword break is used to break out of the case statements advantages of using switch-case statement switch-case statement is preferred by programmers due to the following reasonseasy to debug easy to read and understand ease of maintenance as compared to its equivalent if-else statements like if-else statementsswitch statements can also be nested executes faster than its equivalent if-else construct programming example write program to determine whether the entered character is vowel or not #include int main(char chprintf("\ enter any character ")scanf("% "&ch)switch(chcase ' 'case ' 'printf("\ % is vowel"ch)breakcase ' 'case ' 'printf("\ % is vowel"ch)breakcase ' 'case ' ' |
24,242 | data structures using printf("\ % is vowel"ch)breakcase ' 'case ' 'printf("\ % is vowel"ch)breakcase ' 'case ' 'printf("\ % is vowel"ch)breakdefaultprintf("\ % is not vowel"ch)return output enter any character is not vowel note that there is no break statement after case aso if the character is entered then control will execute the statements given in case iterative statements iterative statements are used to repeat the execution of sequence of statements until the specified expression becomes false supports three types of iterative statements also known as looping statements they are while loop do-while loop for loop in this sectionwe will discuss all these statements while loop the while loop provides mechanism to repeat one or more statements while particular condition is true figure shows the syntax and general form of while loop statement syntax of while loop statement xwhile (conditionstatement blockstatement yupdate the condition expression condition true statement block false statement figure while loop construct |
24,243 | note that in the while loopthe condition is tested before any of the statements in the statement block is executed if the condition is trueonly then the statements will be executedotherwise if the condition is falsethe control will jump to statement ythat is the immediate statement outside the while loop block in the flow diagram of fig it is clear that we need to constantly update the condition of the while loop it is this condition which determines when the loop will end the while loop will execute as long as the condition is true note that if the condition is never updated and the condition never becomes falsethen the computer will run into an infinite loop which is never desirable for examplethe following code prints the first numbers using while loop #include int main(int while( <= printf("\ % " ) /condition updated return note that initially and is less than the condition is trueso in the while loop the value of is printed and its value is incremented by when = the condition becomes false and the loop ends programming example write program to calculate the sum of numbers from to #include int main(int nmisum = printf("\ enter the value of ")scanf("% "& ) =mprintf("\ enter the value of ")scanf("% "& )while( <=nsum sum ii printf("\ the sum of numbers from % to % % "mnsum)return output enter the value of enter the value of the sum of numbers from to do-while loop the do-while loop is similar to the while loop the only difference is that in do-while loopthe test condition is tested at the end of the loop as the test condition is evaluated at the endthis means that the body of the loop gets executed at least one time (even if the condition is falsefigure shows the syntax and the general form of do-while loop |
24,244 | data structures using figure do-while construct note that the test condition is enclosed in parentheses and followed by semi-colon the statements in the statement block are enclosed within curly brackets the curly brackets are optional if there is only one statement in the body of the do-while loop the do-while loop continues to execute while the condition is true and when the condition becomes falsethe control jumps to the statement following the do-while loop the major disadvantage of using do-while loop is that it always executes at least onceso even if the user enters some invalid datathe loop will execute howeverdo-while loops are widely used to print list of options for menu-driven programs for exampleconsider the following code #include int main(int do printf("\ % " ) while( <= )return what do you think will be the outputyesthe code will print numbers from to programming example write program to calculate the average of first numbers #include int main(int ni sum = float avg |
24,245 | printf("\ enter the value of ")scanf("% "& )do sum sum ii while( <= )avg (float)sum/nprintf("\ the sum of first % numbers % ",nsum)printf("\ the average of first % numbers "navg)return output enter the value of the sum of first numbers the average of first numbers for loop like the while and do-while loopsthe for loop provides mechanism to repeat task till particular condition is true the synax and general form of for loop is given in fig initialization of loop variable syntax of for loop for (initializationconditionincrement/decrement/updatestatement blockstatement ycontrolling condition for loop variable false true statement block update the loop variable statement figure for loop construct when for loop is usedthe loop variable is initialized only once with every iterationthe value of the loop variable is updated and the condition is checked if the condition is truethe statement block of the loop is executedelse the statements comprising the statement block of the for loop are skipped and the control jumps to the statement following the for loop body in the syntax of the for loopinitialization of the loop variable allows the programmer to give it value secondthe condition specifies that while the conditional expression is truethe loop |
24,246 | data structures using should continue to repeat itself every iteration of the loop must make the condition to exit the loop approachable sowith every iterationthe loop variable must be updated updating the loop variable may include incrementing the loop variabledecrementing the loop variable or setting it to some other value likei += where is the loop variable note that every section of the for loop is separated from the other with semi-colon it is possible that one of the sections may be emptythough the semi-colons still have to be there howeverif the condition is emptyit is evaluated as true and the loop will repeat until something else stops it the for loop is widely used to execute single or group of statements for limited number of times the following code shows how to print the first numbers using for loop #include int main(int inprintf("\ enter the value of :")scanf("% "& )for( = ; <= ; ++printf("\ % " )return in the codei is the loop variable initiallyit is initialized with suppose the user enters as the value of then the condition is checkedsince the condition is true as is less than nthe statement in the for loop is executed and the value of is printed after every iterationthe value of is incremented when exceeds the value of nthe control jumps to the return statement programming example write program to determine whether given number is prime or composite number #include #include int main(int flag inumclrscr()printf("\ enter any number ")scanf("% "&num)for( = <num/ ; ++if(num% = flag = breakif(flag = printf("\ % is composite number"num)else printf("\ % is prime number"num)return output enter any number is prime number |
24,247 | break and continue statements break statement in cthe break statement is used to terminate the execution of the nearest enclosing loop in which it appears we have already seen its use in the switch statement the break statement is widely used with forwhileand do-while loops when the compiler encounters break statementthe control passes to the statement that follows the loop in which the break statement appears its syntax is quite simplejust type keyword break followed by semi-colon breakthe example given below shows the manner in which break statement is used to terminate the loop in which it is embedded #include int main(int while( <= if ( == breakprintf("\ % " ) return output as soon as becomes equal to the break statement is executed and the control jumps to the statement following the while loop hencethe break statement is used to exit loop from any point within its bodybypassing its normal termination expression continue statement like the break statementthe continue statement can only appear in the body of loop when the compiler encounters continue statementthen the rest of the statements in the loop are skipped and the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing loop its syntax is quite simplejust type keyword continue followed by semi-colon continueagain like the break statementthe continue statement cannot be used without an enclosing forwhileor do-while loop when the continue statement is encountered in the while loop and in the do-while loopthe control is transferred to the code that tests the controlling expression howeverif placed within for loopthe continue statement causes branch to the code that updates the loop variable for exampleconsider the following code#include int main(int ifor( = < ++if ( == |
24,248 | data structures using continueprintf("\ % " )return output note that the code is meant to print numbers from to but as soon as becomes equal to the continue statement is encounteredso the printf(statement is skipped and the control passes to the expression that increments the value of hencewe conclude that the continue statement is somewhat the opposite of the break statement it forces the next iteration of the loop to take placeskipping any code in between itself and the test condition of the loop it is generally used to restart statement sequence when an error occurs functions enables its programmers to break up program into segments commonly known as functionseach of which can be written more or less independently of the others every function in the program is supposed to perform well-defined task thereforethe program code of one function is completely insulated from the other functions every function interfaces to the outside world in terms of how information is transferred to it main(func (and how results generated by the function are statement blocktransmitted back from it this interface is basically specified by the function name for examplelook func ()at fig which explains how the main(function calls another function to perform well-defined return task in the figurewe can see that main(calls function named func (thereforemain(is figure main(calls func (known as the calling function and func (is known as the called function the moment the compiler encounters function callthe control jumps to the statements that are part of the called function after the called function is executedthe control is returned to the calling program the main(function can call as many functions as it wants and as many times as it wants for examplea function call placed within for loopwhile loopor do-while loop may call the same function multiple times till the condition holds true not only main()any function can call any other function for examplelook at fig which shows one function calling anotherand the other function in turn calling some other function main(func ()return figure func (func ()returnfunction calling another function func (func ()returnfunc (return |
24,249 | why are functions neededlet us analyse the reasons why segmenting program into manageable chunks is an important aspect of programming dividing the program into separate well-defined functions facilitates each function to be written and tested separately this simplifies the process of getting the total program to work understandingcodingand testing multiple separate functions is easier than doing the same for one big function if big program has to be developed without using any function other than main()then there will be countless lines in the main(function and maintaining that program will be difficult task all the libraries in contain set of functions that the programmers are free to use in their programs these functions have been pre-written and pre-testedso the programmers can use them without worrying about their code details this speeds up program developmentby allowing the programmer to concentrate only on the code that he has to write like librariesprogrammers can also write their own functions and use them from different points in the main program or any other program that needs its functionalities when big program is broken into comparatively smaller functionsthen different programmers working on that project can divide the workload by writing different functions using functions function can be compared to black box that takes in inputsprocesses itand then outputs the result howeverwe may also have function that does not take any inputs at allor function that does not return any value at all while using functionswe will be using the following terminologiesa function that uses another function is known as the calling functionand is known as the called function the inputs that function takes are known as arguments when called function returns some result back to the calling functionit is said to return that result the calling function may or may not pass parameters to the called function if the called function accepts argumentsthe calling function will pass parameterselse not function declaration is declaration statement that identifies function' namea list of arguments that it acceptsand the type of data it returns function definition consists of function header that identifies the functionfollowed by the body of the function containing the executable code for that function function declaration before using functionthe compiler must know the number of parameters and the type of parameters that the function expects to receive and the data type of value that it will return to the calling program placing the function declaration statement prior to its use enables the compiler to make check on the arguments used while calling that function the general format for declaring function that accepts arguments and returns value as result can be given asreturn_data_type function_name(data_type variable data_type variable )herefunction_name is valid name for the function naming function follows the same rules that are followed while naming variables function should have meaningful name that must specify the task that the function will perform |
24,250 | data structures using return_data_type specifies the data type of the value that will be returned to the calling function as result of the processing performed by the called function (data_type variable data_type variable is list of variables of specified data types these variables are passed from the calling function to the called function they are also known as arguments or parameters that the called function accepts to perform its task note function having void as its return type cannot return any value similarlya function having void as its parameter list cannot accept any value function definition when function is definedspace is allocated for that function in the memory function definition comprises of two partsfunction header function body the syntax of function definition can be given asreturn_data_type function_name(data_type variable data_type variable statements return(variable)note that the number of arguments and the order of arguments in the function header must be the same as that given in the function declaration statement while return_data_type function_name(data_type variable data_type variable is known as the function headerthe rest of the portion comprising of program statements within the curly brackets is the function body which contains the code to perform the specific task note that the function header is same as the function declaration the only difference between the two is that function header is not followed by semi-colon function call the function call statement invokes the function when function is invokedthe compiler jumps to the called function to execute the statements that are part of that function once the called function is executedthe program control passes back to the calling function function call statement has the following syntaxfunction_name(variable variable )the following points are to be noted while calling functionfunction name and the number and the type of arguments in the function call must be same as that given in the function declaration and the function header of the function definition names (and not the typesof variables in function declarationfunction calland header of function definition may vary arguments may be passed in the form of expressions to the called function in such casearguments are first evaluated and converted to the type of formal parameter and then the body of the function gets executed if the return type of the function is not voidthen the value returned by the called function may be assigned to some variable as given below variable_name function_name(variable variable ) |
24,251 | programming example write program to find whether number is even or odd using functions #include int evenodd(int)//function declaration int main(int numflagprintf("\ enter the number ")scanf("% "&num)flag evenodd(num)//function call if (flag = printf("\ % is even"num)else printf("\ % is odd"num)return int evenodd(int /function header /function body if( % = return else retun output enter the number is even passing parameters to functions there are two ways in which arguments or parameters can be passed to the called function call by value the values of the variables are passed by the calling function to the called function call by reference the addresses of the variables are passed by the calling function to the called function call by value in this methodthe called function creates new variables to store the value of the arguments passed to it thereforethe called function uses copy of the actual arguments to perform its intended task if the called function is supposed to modify the value of the parameters passed to itthen the change will be reflected only in the called function in the calling functionno change will be made to the value of the variables this is because all the changes are made to the copy of the variables and not to the actual variables to understand this conceptconsider the code given below the function add(accepts an integer variable num and adds to it in the calling functionthe value of num in add()the value of num is modified to but in the calling functionthe change is not reflected #include void add(int )int main(int num printf("\ the value of num before calling the function % "num)add(num) |
24,252 | data structures using printf("\ the value of num after calling the function % "num)return void add(int nn printf("\ the value of num in the called function % " )output the value of num before calling the function the value of num in the called function the value of num after calling the function following are the points to remember while passing arguments to function using the call-byvalue methodwhen arguments are passed by valuethe called function creates new variables of the same data type as the arguments passed to it the values of the arguments passed by the calling function are copied into the newly created variables values of the variables in the calling functions remain unaffected when the arguments are passed using the call-by-value technique pros and cons the biggest advantage of using the call-by-value technique is that arguments can be passed as variablesliteralsor expressionswhile its main drawback is that copying data consumes additional storage space in additionit can take lot of time to copythereby resulting in performance penaltyespecially if the function is called many times call by reference when the calling function passes arguments to the called function using the call-by-value methodthe only way to return the modified value of the argument to the caller is explicitly using the return statement better option is to pass arguments using the call-by-reference technique in this methodwe declare the function parameters as references rather than normal variables when this is doneany changes made by the function to the arguments it received are also visible in the calling function to indicate that an argument is passed using call by referencean asterisk (*is placed after the type in the parameter list hencein the call-by-reference methoda function receives an implicit reference to the argumentrather than copy of its value thereforethe function can modify the value of the variable and that change will be reflected in the calling function as well the following code illustrates this concept #include void add(int *)int main(int num printf("\ the value of num before calling the function % "num)add(&num)printf("\ the value of num after calling the function % "num)return void add(int * |
24,253 | * * printf("\ the value of num in the called function % "* )output the value of num before calling the function the value of num in the called function the value of num after calling the function advantages the advantages of using the call-by-reference technique of passing arguments includesince arguments are not copied into the new variablesit provides greater time and spaceefficiency the function can change the value of the argument and the change is reflected in the calling function function can return only one value in case we need to return multiple valueswe can pass those arguments by referenceso that the modified values are visible in the calling function disadvantages howeverthe drawback of using this technique is that if inadvertent changes are caused to variables in called function then these changes would be reflected in calling function as original values would have been overwritten consider the code given below which swaps the value of two integers note the value of integers in the calling function and called function //this function swaps the value of two variables #include void swap_call_val(intint)void swap_call_ref(int *int *)int main(int = = = = printf("\ in main() % and % "ab)swap_call_val(ab)printf("\ in main() % and % "ab)printf("\ \ in main() % and % "cd)swap_call_ref(& & )printf("\ in main() % and % "cd)return void swap_call_val(int aint bint temptemp aa bb tempprintf("\ in function (call by value methoda % and % "ab)void swap_call_ref(int *cint *dint temptemp * * * * tempprintf("\ in function (call by reference methodc % and % "* * ) |
24,254 | data structures using output in main() and in function (call by value methoda and in main() and in main() and in function (call by reference methodc and in main() and pointers every variable in has name and value associated with it when variable is declareda specific block of memory within the computer is allocated to hold the value of that variable the size of the allocated block depends on the data type consider the following statement int when this statement executesthe compiler sets aside bytes of memory to hold the value it also sets up symbol table in which it adds the symbol and the relative address in the memory where those bytes were set aside (note the size of integer may vary from one system to another on bit systemsinteger variable is allocated bytes while on bit systems it is allocated bytes thusevery variable in has value and also memory location (commonly known as addressassociated with it we will use terms rvalue and lvalue for the value and the address of the variablerespectively the rvalue appears on the right side of the assignment statement ( in the above statementand cannot be used on the left side of the assignment statement thereforewriting kis illegal if we writeint xyx xthenwe have two integer variables and the compiler reserves memory for the integer variable and stores the rvalue in it when we say xthen is interpreted as its rvalue since it is on the right hand side of the assignment operator thereforehere refers to the value stored at the memory location set aside for xin this case after this statement is executedthe rvalue of is also you must be wondering why we are discussing addresses and lvalues actually pointers are nothing but memory addresses pointer is variable that contains the memory location of another variable thereforea pointer is variable that represents the location of data itemsuch as variable or an array element pointers are frequently used in cas they have number of useful applications these applications includepointers are used to pass information back and forth between functions pointers enable the programmers to return multiple data items from function via function arguments pointers provide an alternate way to access the individual elements of an array pointers are used to pass arrays and strings as function arguments we will discuss this in subsequent pointers are used to create complex data structuressuch as treeslinked listslinked stackslinked queuesand graphs |
24,255 | pointers are used for the dynamic memory allocation of variable (refer appendix on memory allocation in programsdeclaring pointer variables the general syntax of declaring pointer variables can be given as below data_type *ptr_nameheredata_type is the data type of the value that the pointer will point to for exampleint *pnumchar *pchfloat *pfnumin each of the above statementsa pointer variable is declared to point to variable of the specified data type although all these pointers (pnumpchand pfnumpoint to different data typesthey will occupy the same amount of space in the memory but how much space they will occupy will depend on the platform where the code is going to run now let us declare an integer pointer variable and start using it in our program code int int *ptrptr &xin the above statementptr is the name of the pointer variable the informs the compiler that ptr is pointer variable and the int specifies that it will store the address of an integer variable an integer pointer variabletherefore'points toan integer variable in the last statementptr is assigned the address of the operator retrieves the lvalue (addressof xand copies that to the contents of the pointer ptr consider the memory cells given in fig figure memory representation nowsince is an integer variableit will be allocated bytes assuming that the compiler assigns it memory locations and the address of (written as &xis equal to that is the starting address of in the memory when we writeptr &xthen ptr we can 'dereferencea pointeri we can refer to the value of the variable to which it points by using the unary operator as in *ptr that is*ptr since is the value of look at the following code which shows the use of pointer variable#include int main(int num*pnumpnum &numprintf("\ enter the number ")scanf("% "&num)printf("\ the number that was entered is % "*pnum)return output enter the number the number that was entered is what will be the value of *(&num)it is equivalent to simply writing num |
24,256 | data structures using pointer expressions and pointer arithmetic like other variablespointer variables can also be used in expressions for exampleif ptr and ptr are pointersthen the following statements are validint num num sum mul div int *ptr *ptr ptr &num ptr &num sum *ptr *ptr mul sum (*ptr )*ptr + div (*ptr )/(*ptr in cthe programmer may add integers to or subtract integers from pointers as well as subtract one pointer from the other we can also use shorthand operators with the pointer variables as we use them with other variables also allows comparing pointers by using relational operators in the expressions for examplep = and are all valid in postfix unary increment (++and decrement (--operators have greater precedence than the dereference operator (*thereforethe expression *ptr+is equivalent to *(ptr++)as +has greater operator precedence than thusthe expression will increase the value of ptr so that it now points to the next memory location this means that the statement *ptr+does not do the intended task thereforeto increment the value of the variable whose address is stored in ptryou should write (*ptr)+null pointers so farwe have studied that pointer variable is pointer to variable of some data type howeverin some caseswe may prefer to have null pointer which is special pointer value and does not point to any value this means that null pointer does not point to any valid memory address to declare null pointeryou may use the predefined constant null which is defined in several standard header files including and after including any of these files in your programyou can write int *ptr nullyou can always check whether given pointer variable stores the address of some variable or contains null by writingif (ptr =nullstatement blockyou may also initialize pointer as null pointer by using the constant int *ptrptr this is valid statement in as null is preprocessor macrowhich typically has the value or replacement text howeverto avoid ambiguityit is always better to use null to declare null pointer function that returns pointer values can return null pointer when it is unable to perform its task generic pointers generic pointer is pointer variable that has void as its data type the void pointeror the generic pointeris special type of pointer that can point to variables of any data type it is declared like normal pointer variable but using the void keyword as the pointer' data type for examplewww allitebooks com |
24,257 | void *ptrin csince you cannot have variable of type voidthe void pointer will therefore not point to any data andthuscannot be dereferenced you need to cast void pointer to another kind of pointer before using it generic pointers are often used when you want pointer to point to data of different types at different times for exampletake look at the following code #include int main(int = char ch ' 'void *gpgp &xprintf("\ generic pointer points to the integer value % "*(int*)gp)gp &chprintf("\ generic pointer now points to the character% "*(char*)gp)return output generic pointer points to the integer value generic pointer now points to the character it is always recommended to avoid using void pointers unless absolutely necessaryas they effectively allow you to avoid type checking programming example write program to add two integers using pointers and functions #include void sum (int*int*int*)int main(int num num totalprintf("\ enter the first number ")scanf("% "&num )printf("\ enter the second number ")scanf("% "&num )sum(&num &num &total)printf("\ total % "total)return void sum (int *aint *bint * * * *boutput enter the first number enter the second number total pointer to pointers in cyou can also use pointers that point to pointers the pointers in turn point to data or even to other pointers to declare pointers to pointersjust add an asterisk for each level of reference |
24,258 | data structures using for exampleconsider the following codeint = int *px**ppxpx &xppx &pxfigure pointer to pointer now if we writelet us assumethe memory locations of these variables are as shown in fig printf("\ % "**ppx)thenit would print the value of drawbacks of pointers although pointers are very useful in cthey are not free from limitations if used incorrectlypointers can lead to bugs that are difficult to unearth for exampleif you use pointer to read memory location but that pointer is pointing to an incorrect locationthen you may end up reading wrong value an erroneous input always leads to an erroneous output thus however efficient your program code may bethe output will always be disastrous same is the case when writing value to particular memory location let us try to find some common errors when using pointers int *pxx= *px errorun-initialized pointer px is pointing to an unknown memory location hence it will overwrite that location' contents and store in it int *pxx= px xerrorit should be px &xint = = *px*pypx &xpy &yif(px<pyprintf("\ is less than ")else printf("\ is less than ")errorit should be if(*px*pypoints to remember was developed in the early by dennis ritchie at bell laboratories every word in program is either an identifier or keyword identifiers are the names given to program elements such as variables and functions keywords are reserved words which cannot be used as identifiers provides four basic data typescharintfloatand double variable is defined as meaningful name given to data storage location in computer memory standard library function scanf(is used to input data in specified format printf()function is used to output data of different types in specified format supports different types of operators which can be classified into following categoriesarithmeticrelationalequalitylogicalunaryconditionalbitwiseassignmentcommaand sizeof operators |
24,259 | modulus operator (%can only be applied on integer operandsand not on float or double operands equality operators have lower precedence than relational operators like arithmetic expressionslogical expressions are evaluated from left to right both +and ++ increment the value of xbut in the former casethe value of is returned before it is incremented whereas in the latter casethe value of is returned after it is incremented conditional operator is also known as ternary operator as it takes three operands bitwise not or complement produces one' complement of given binary number among all the operatorscomma operator has the lowest precedence sizeof is unary operator used to calculate the size of data types this operator can be applied to all data types while type conversion is done implicitlytypecasting has to be done explicitly by the programmer typecasting is done when the value of one data type has to be converted into the value of another data type supports three types of control statementsdecision control statementsiterative statementsand jump statements in switch statementif the value of the variable does not match with any of the values of case statementsthen default case is executed iterative statements are used to repeat the execution of list of statements until the specified expression becomes false the break statement is used to terminate the execution of the nearest enclosing loop in which it appears when the compiler encounters continue statementthen the rest of the statements in the loop are skipped and the control is unconditionally transferred to the loop-continuation portion of the nearest enclosing loop program contains one or more functionswhere each function is defined as group of statements that perform specific task every program contains main(function which is the starting point of the program it is the function that is called by the operating system when the user runs the program function declaration statement identifies function' name and the list of arguments that it accepts and the type of data it returns function definitionon the other handconsists of function header that identifies the functionfollowed by the body of the function containing the executable code for that function when function is definedspace is allocated for that function in the memory the moment the compiler encounters function callthe control jumps to the statements that are part of the called function after the called function is executedthe control is returned back to the calling function placing the function declaration statement prior to its use enables the compiler to make check on the arguments used while calling that function function having void as its return type cannot return any value similarlya function having void as its parameter list cannot accept any value call by value method passes values of the variables to the called function thereforethe called function uses copy of the actual arguments to perform its intended task this method is used when the function does not need to modify the values of the original variables in the calling function in call by reference methodaddresses of the variables are passed by the calling function to the called function hencein this methoda function receives an implicit reference to the argumentrather than copy of its value this allows the function to modify the value of the variable and that change is reflected in the calling function as well pointer is variable that contains the memory address of another variable the operator retrieves the address of the variable we can 'dereferencea pointeri refer to the value of the variable to which it points by using unary operator null pointer is special pointer variable that does not point to any variable this means that null pointer does not point to any valid memory address to declare null pointer we may use the predefined constant null generic pointer is pointer variable that has void as its data type the generic pointer can point to variables of any data type to declare pointer to pointerswe need to add an asterisk (*for each level of reference |
24,260 | data structures using exercises review questions discuss the structure of program differentiate between declaration and definition how is memory reserved using declaration statement what do you understand by identifiers and keywords explain the terms variables and constants how many types of variables are supported by what does the data type of variable signify write short note on basic data types that the language supports why do we include in our programs what are header filesexplain their significance write short notes on printf and scanf functions write short note on operators available in language draw the operator precedence chart differentiate between typecasting and type conversion what are decision control statementsexplain in detail write short note on the iterative statements that language supports when will you prefer to work with switch statement define function why are they needed differentiate between function declaration and function definition why is function declaration statement placed prior to function definition explain the concept of making function calls differentiate between call by value and call by reference using suitable examples write short note on pointers explain the difference between null pointer and void pointer how are generic pointers different from other pointer variables write short note on pointers to pointers programming exercises write program to read integers display these numbers by printing three numbers in line separated by commas write program to print the count of even numbers between - also print their sum write program to count the number of vowels in text write program to read the address of user display the result by breaking it in multiple lines write program to read two floating point numbers add these numbers and assign the result to an integer finallydisplay the value of all the three variables write program to read floating point number display the rightmost digit of the integral part of the number write program to calculate simple interest and compound interest write program to calculate salary of an employee given his basic pay (to be entered by the user)hra of the basic payta of basic pay define hra and ta as constants and use them to calculate the salary of the employee write program to prepare grocery bill enter the name of the items purchasedquantity in which it is purchasedand its price per unit then display the bill in the following format*********** ***********item quantity price amount total amount to be paid write program using printf statement to print bye in the following formatbbb bbb eeee eeee write program to read an integer display the value of that integer in decimaloctaland hexadecimal notation write program that prints floating point value in exponential format with the following specifications(acorrect to two decimal places(bcorrect to four decimal placesand |
24,261 | (ccorrect to eight decimal places write program to find the smallest of three integers using functions write program to calculate area of triangle using function write program to find whether number is divisible by two or not using functions write program to print 'programming in is funusing pointers write program to read character and print it also print its ascii value if the character is in lower caseprint it in upper case and vice versa repeat the process until '*is entered write program to add three floating point numbers the result should contain only two digits after the decimal write program to take input from the user and then check whether it is number or character if it is characterdetermine whether it is in upper case or lower case also print its ascii value write program to display sum and average of numbers from to use for loop write program to print all odd numbers from to write program to print all prime numbers from to write program to read numbers until - is entered and display whether it is an armstrong number or not write program to add two floating point numbers using pointers and functions write program to calculate area of triangle using pointers multiple-choice questions the operator which compares two values is (aassignment (brelational (cunary (dequality ternary operator operates on how many operands( ( ( ( which operator produces the one' complement of the given binary value(alogical and (bbitwise and (clogical or (dbitwise not which operator has the lowest precedence(asizeof (bunary (cassignment (dcomma which of the following is the conversion character associated with short integer( % ( % ( % ( % which of the following is not character constant( ' ( " ( ( '* which of the following is valid variable name(ainitial name (ba+ ( $amt (dfloats which operator cannot be used with floating point numbers( ( ( ( identify the erroneous expression (ax= = (bres ++ (cres / (dres +- * function declaration statement identifies function with its (aname (barguments (cdata type of return value (dall of these which return type cannot return any value to the calling function(aint (bfloat (cvoid (ddouble memory is allocated for function when the function is (adeclared (bdefined (ccalled (dreturned *(&numis equivalent to writing ( &num ( *num (cnum (dnone of these which operator retrieves the lvalue of variable( ( ( -(dnone of these which operator is used to dereference pointer( ( ( -(dnone of these true or false we can have only one function in program keywords are case sensitive variable 'firstis the same as 'first signed variables can increase the maximum positive range comment statements are not executed by the compiler |
24,262 | data structures using equality operators have higher precedence than the relational operators shifting once to the left multiplies the number by decision control statements are used to repeat the execution of list of statements printf("% "scanf("% "&num))is valid statement , is valid integer constant printf statement can generate only one line of output stdio is used to store the source code of the program the closing brace of main(is the logical end of the program the declaration section gives instructions to the computer any valid printable ascii character can be used for variable name underscore can be used anywhere in the variable name void is data type in all arithmetic operators have same precedence the modulus operator can be used only with integers the calling function always passes parameters to the called function the name of function is global no function can be declared within the body of another function the operator retrieves the lvalue of the variable unary increment and decrement operators have greater precedence than the dereference operator on -bit systemsan integer variable is allocated bytes fill in the blanks was developed by the execution of program begins at in the memorycharacters are stored as return returns to the finds the remainder of an integer division sizeof is operator used to calculate the sizes of data types is also known as forced conversion is executed when the value of the variable does not match with any of the values of the case statement function prints data on the monitor program ends with causes the cursor to move to the next line variable can be made constant by declaring it with the qualifier at the time of initialization operator returns the number of bytes occupied by the operand the specification is used to read/write short integer the specification is used to read/write hexadecimal integer to print the data left-justifiedspecification is used after the function is executedthe control passes back to the function that uses another function is known as the the inputs that the function takes are known as function definition consist of and in methodaddress of the variable is passed by the calling function to the called function size of character pointer is pointer does not point to any valid memory address the appears on the right side of the assignment statement the operator informs the compiler that the variable is pointer variable |
24,263 | introduction to data structures and algorithms learning objective in this we are going to discuss common data structures and algorithms which serve as building blocks for creating efficient programs we will also discuss different approaches to designing algorithms and different notations for evaluating the performance of algorithms basic terminology we have already learnt the basics of programming in in the previous and know how to writedebugand run simple programs in language our aim has been to design good programswhere good program is defined as program that runs correctly is easy to read and understand is easy to debug and is easy to modify program should undoubtedly give correct resultsbut along with that it should also run efficiently program is said to be efficient when it executes in minimum time and with minimum memory space in order to write efficient programs we need to apply certain data management concepts the concept of data management is complex task that includes activities like data collectionorganization of data into appropriate structuresand developing and maintaining routines for quality assurance data structure is crucial part of data management and in this book it will be our prime concern data structure is basically group of data elements that are put together under one nameand which defines particular way of storing and organizing data in computer so that it can be used efficiently |
24,264 | data structures using data structures are used in almost every program or software system some common examples of data structures are arrayslinked listsqueuesstacksbinary treesand hash tables data structures are widely applied in the following areascompiler design statistical analysis package numerical analysis artificial intelligence operating system dbms simulation graphics when you will study dbms as subjectyou will realize that the major data structures used in the network data model is graphshierarchical data model is treesand rdbms is arrays specific data structures are essential ingredients of many efficient algorithms as they enable the programmers to manage huge amounts of data easily and efficiently some formal design methods and programming languages emphasize data structures and the algorithms as the key organizing factor in software design this is because representing information is fundamental to computer science the primary goal of program or software is not to perform calculations or operations but to store and retrieve information as fast as possible be it any problem at handthe application of an appropriate data structure provides the most efficient solution solution is said to be efficient if it solves the problem within the required resource constraints like the total space available to store the data and the time allowed to perform each subtask and the best solution is the one that requires fewer resources than known alternatives moreoverthe cost of solution is the amount of resources it consumes the cost of solution is basically measured in terms of one key resource such as timewith the implied assumption that the solution meets the other resource constraints today computer programmers do not write programs just to solve problem but to write an efficient program for thisthey first analyse the problem to determine the performance goals that must be achieved and then think of the most appropriate data structure for that job howeverprogram designers with poor understanding of data structure concepts ignore this analysis step and apply data structure with which they can work comfortably the applied data structure may not be appropriate for the problem at hand and therefore may result in poor performance (like slow speed of operationsconverselyif program meets its performance goals with data structure that is simple to usethen it makes no sense to apply another complex data structure just to exhibit the programmer' skill when selecting data structure to solve problemthe following steps must be performed analysis of the problem to determine the basic operations that must be supported for examplebasic operation may include inserting/deleting/searching data item from the data structure quantify the resource constraints for each operation select the data structure that best meets these requirements this three-step approach to select an appropriate data structure for the problem at hand supports data-centred view of the design process in the approachthe first concern is the data and the operations that are to be performed on them the second concern is the representation of the dataand the final concern is the implementation of that representation there are different types of data structures that the language supports while one type of data structure may permit adding of new data items only at the beginningthe other may allow it to be added at any position while one data structure may allow accessing data items sequentiallythe other may allow random access of data soselection of an appropriate data structure for the problem is crucial decision and may have major impact on the performance of the program |
24,265 | elementary data structure organization data structures are building blocks of program program built using improper data structures may not work as expected so as programmer it is mandatory to choose most appropriate data structures for program the term data means value or set of values it specifies either the value of variable or constant ( marks of studentsname of an employeeaddress of customervalue of pietc while data item that does not have subordinate data items is categorized as an elementary itemthe one that is composed of one or more subordinate data items is called group item for examplea student' name may be divided into three sub-items--first namemiddle nameand last name--but his roll number would normally be treated as single item record is collection of data items for examplethe nameaddresscourseand marks obtained are individual data items but all these data items can be grouped together to form record file is collection of related records for exampleif there are students in classthen there are records of the students all these related records are stored in file similarlywe can have file of all the employees working in an organizationa file of all the customers of companya file of all the suppliersso on and so forth moreovereach record in file may consist of multiple data items but the value of certain data item uniquely identifies the record in the file such data item is called primary keyand the values in such field are called keys or key values for examplein student' record that contains roll numbernameaddresscourseand marks obtainedthe field roll number is primary key rest of the fields (nameaddresscourseand markscannot serve as primary keyssince two or more students may have the same nameor may have the same address (as they might be staying at the same place)or may be enrolled in the same courseor have obtained same marks this organization and hierarchy of data is taken further to form more complex types of data structureswhich is discussed in section classification of data structures data structures are generally categorized into two classesprimitive and non-primitive data structures primitive and non-primitive data structures primitive data structures are the fundamental data types which are supported by programming language some basic data types are integerrealcharacterand boolean the terms 'data type''basic data type'and 'primitive data typeare often used interchangeably non-primitive data structures are those data structures which are created using primitive data structures examples of such data structures include linked listsstackstreesand graphs non-primitive data structures can further be classified into two categorieslinear and non-linear data structures linear and non-linear structures if the elements of data structure are stored in linear or sequential orderthen it is linear data structure examples include arrayslinked listsstacksand queues linear data structures can be represented in memory in two different ways one way is to have to linear relationship between elements by means of sequential memory locations the other way is to have linear relationship between elements by means of links |
24,266 | data structures using howeverif the elements of data structure are not stored in sequential orderthen it is non-linear data structure the relationship of adjacency is not maintained between elements of non-linear data structure examples include trees and graphs supports variety of data structures we will now introduce all these data structures and they would be discussed in detail in subsequent arrays an array is collection of similar data elements these data elements have the same data type the elements of the array are stored in consecutive memory locations and are referenced by an index (also known as the subscriptin carrays are declared using the following syntaxtype name[size]for exampleint marks[ ]the above statement declares an array marks that contains elements in cthe array index starts from zero this means that the array marks will contain elements in all the first element will be stored in marks[ ]second element in marks[ ]so on and so forth thereforethe last elementthat is the th elementwill be stored in marks[ in the memorythe array will be stored as shown in fig st nd rd th th th th th th th element element element element element element element element element element marks[ marks[ marks[ marks[ marks[ marks[ marks[ marks[ marks[ marks[ figure memory representation of an array of elements arrays are generally used when we want to store large amount of similar type of data but they have the following limitationsarrays are of fixed size data elements are stored in contiguous memory locations which may not be always available insertion and deletion of elements can be problematic because of shifting of elements from their positions howeverthese limitations can be solved by using linked lists we will discuss more about arrays in linked lists linked list is very flexibledynamic data structure in which elements (called nodesform sequential list in contrast to static arraysa programmer need not worry about how many elements will be stored in the linked list this feature enables the programmers to write robust programs which require less maintenance in linked listeach node is allocated space as it is added to the list every node in the list points to the next node in the list thereforein linked listevery node contains the following two types of datathe value of the node or any other data that corresponds to that node pointer or link to the next node in the list |
24,267 | the last node in the list contains null pointer to indicate that it is the end or tail of the list since the memory for node is dynamically allocated when it is added to the listthe total number of nodes that may be added to list is limited only by the amount of memory available figure shows linked list of seven nodes figure simple linked list note advantageeasier to insert or delete data elements disadvantageslow search operation and requires more memory space stacks stack is linear data structure in which insertion and deletion of elements are done at only one endwhich is known as the top of the stack stack is called last-infirst-out (lifostructure because the last element which is added to the stack is the first element which is deleted from the stack in the computer' memorystacks can be implemented using arrays or linked lists figure shows the array implementation of stack every stack has variable top associated with it top is used to store the address of the topmost element of the stack it is this position from where the element will be added or deleted there is another variable maxwhich is used to store the maximum number of elements that the stack can store if top nullthen it indicates that the stack is empty and if top max- then the stack is full ab abc abcd abcde top figure array representation of stack in fig top so insertions and deletions will be done at this position herethe stack can store maximum of elements where the indices range from - in the above stackfive more elements can still be stored stack supports three basic operationspushpopand peep the push operation adds an element to the top of the stack the pop operation removes the element from the top of the stack and the peep operation returns the value of the topmost element of the stack (without deleting ithoweverbefore inserting an element in the stackwe must check for overflow conditions an overflow occurs when we try to insert an element into stack that is already full similarlybefore deleting an element from the stackwe must check for underflow conditions an underflow condition occurs when we try to delete an element from stack that is already empty queues queue is first-infirst-out (fifodata structure in which the element that is inserted first is the first one to be taken out the elements in queue are added at one end called the rear and removed from the other end called the front like stacksqueues can be implemented by using either arrays or linked lists every queue has front and rear variables that point to the position from where deletions and insertions can be donerespectively consider the queue shown in fig |
24,268 | data structures using front rear figure array representation of queue herefront and rear if we want to add one more value to the listsayif we want to add another element with the value then the rear would be incremented by and the value would be stored at the position pointed by the rear the queueafter the additionwould be as shown in fig herefront and rear every time new element is to be addedwe will repeat the same procedure front rear figure queue after insertion of new element nowif we want to delete an element from the queuethen the value of front will be incremented deletions are done only from this end of the queue the queue after the deletion will be as shown in fig front rear figure queue after deletion of an element howeverbefore inserting an element in the queuewe must check for overflow conditions an overflow occurs when we try to insert an element into queue that is already full queue is full when rear max where max is the size of the queuethat is max specifies the maximum number of elements in the queue note that we have written max because the index starts from similarlybefore deleting an element from the queuewe must check for underflow conditions an underflow condition occurs when we try to delete an element from queue that is already empty if front null and rear nullthen there is no element in the queue trees tree is non-linear data structure which consists of collection of nodes arranged in hierarchical order one of the nodes is designated as the root nodeand the remaining nodes can be partitioned into disjoint sets such that each set is sub-tree of the root the simplest form of tree is binary tree binary tree consists of root node and left and right sub-treeswhere both sub-trees are also binary trees each node contains data elementa left pointer which points to the left sub-treeand right pointer which points to the right sub-tree the root element is the topmost node which is pointed by 'rootpointer if root null then the tree is empty figure shows binary treewhere is the root node and and are the left and right subtrees of if is non-emptythen is said to be the left successor of likewiseif is non-emptythen it is called the right successor of |
24,269 | in fig node is the left child and node is the right child of the root node note that the left sub-tree of the root node consists of the nodes and similarlythe right sub-tree of the root node consists of the nodes and note advantageprovides quick searchinsertand delete operations disadvantagecomplicated deletion algorithm graphs graph is non-linear data structure which is collection of vertices (also called nodesand edges that connect these vertices graph is often viewed as generalization of the tree structurewhere instead of purely parent-to-child relationship between tree nodesany kind of complex relationships between the nodes can exist in tree structurenodes can have any number of children but only one parenta graph on the other hand relaxes all such kinds of restrictions figure shows graph with five nodes node in the graph may represent city and the edges connecting the nodes can represent roads graph can also be used to represent computer network where the nodes are workstations and the edges are the network connections graphs have so many applications in computer science and mathematics that several algorithms have been written to perform the standard graph operationssuch as searching the graph and finding the shortest path between the nodes of graph note that unlike treesgraphs do not have any root node ratherevery node in the graph can be connected with every another node in the graph when two nodes are connected via an edgethe two nodes are known as neighbours for examplein fig node has two neighboursb and figure binary tree figure graph note advantagebest models real-world situations disadvantagesome algorithms are slow and very complex operations on data structures this section discusses the different operations that can be performed on the various data structures previously mentioned traversing it means to access each data item exactly once so that it can be processed for exampleto print the names of all the students in class searching it is used to find the location of one or more data items that satisfy the given constraint such data item may or may not be present in the given collection of data items for exampleto find the names of all the students who secured marks in mathematics inserting it is used to add new data items to the given list of data items for exampleto add the details of new student who has recently joined the course deleting it means to remove (deletea particular data item from the given collection of data items for exampleto delete the name of student who has left the course sorting data items can be arranged in some order like ascending order or descending order depending on the type of application for examplearranging the names of students in class in an alphabetical orderor calculating the top three winners by arranging the participantsscores in descending order and then extracting the top three merging lists of two sorted data items can be combined to form single list of sorted data items |
24,270 | data structures using many timetwo or more operations are applied simultaneously in given situation for exampleif we want to delete the details of student whose name is xthen we first have to search the list of students to find whether the record of exists or not and if it exists then at which locationso that the details can be deleted from that particular location abstract data type an abstract data type (adtis the way we look at data structurefocusing on what it does and ignoring how it does its job for examplestacks and queues are perfect examples of an adt we can implement both these adts using an array or linked list this demonstrates the 'abstractnature of stacks and queues to further understand the meaning of an abstract data typewe will break the term into 'data typeand 'abstract'and then discuss their meanings data type data type of variable is the set of values that the variable can take we have already read the basic data types in include intcharfloatand double when we talk about primitive type (built-in data type)we actually consider two thingsa data item with certain characteristics and the permissible operations on that data for examplean int variable can contain any whole-number value from - to and can be operated with the operators +-*and in other wordsthe operations that can be performed on data type are an inseparable part of its identity thereforewhen we declare variable of an abstract data type ( stack or queue)we also need to specify the operations that can be performed on it abstract the word 'abstractin the context of data structures means considered apart from the detailed specifications or implementation in can abstract data type can be structure considered without regard to its implementation it can be thought of as 'descriptionof the data in the structure with list of operations that can be performed on the data within that structure the end-user is not concerned about the details of how the methods carry out their tasks they are only aware of the methods that are available to them and are only concerned about calling those methods and getting the results they are not concerned about how they work for examplewhen we use stack or queuethe user is concerned only with the type of data and the operations that can be performed on it thereforethe fundamentals of how the data is stored should be invisible to the user they should not be concerned with how the methods work or what structures are being used to store the data they should just know that to work with stacksthey have push(and pop(functions available to them using these functionsthey can manipulate the data (insertion or deletionstored in the stack advantage of using adts in the real worldprograms evolve as result of new requirements or constraintsso modification to program commonly requires change in one or more of its data structures for exampleif you want to add new field to student' record to keep track of more information about each studentthen it will be better to replace an array with linked structure to improve the program' efficiency in such scenariorewriting every procedure that uses the changed structure is not desirable thereforea better alternative is to separate the use of data structure from the details of its implementation this is the principle underlying the use of abstract data types algorithms the typical definition of algorithm is ' formally defined procedure for performing some calculationif procedure is formally definedthen it can be implemented using formal language |
24,271 | and such language is known as programming language in general termsan algorithm provides blueprint to write program to solve particular problem it is considered to be an effective procedure for solving problem in finite number of steps that isa well-defined algorithm always provides an answer and is guaranteed to terminate algorithms are mainly used to achieve software reuse once we have an idea or blueprint of solutionwe can implement it in any high-level language like cc++or java an algorithm is basically set of instructions that solve problem it is not uncommon to have multiple algorithms to tackle the same problembut the choice of particular algorithm must depend on the time and space complexity of the algorithm different approaches to designing an algorithm algorithms are used to manipulate the data contained in data structures when working with data structuresalgorithms are used to perform operations on the stored data complex algorithm is often divided into smaller units called modules this process of dividing an algorithm into modules is called modularization the key advantages of modularization are as followsit makes the complex algorithm simpler to design and implement each module can be designed independently while designing one modulethe details of other modules can be ignoredthereby enhancing clarity in design which in turn simplifies implementationdebuggingtestingdocumentingand maintenance of the overall algorithm there are two main approaches to design an algorithm--top-down approach and bottom-up approachas shown in fig complex algorithm top-down approach module module bottom-up approach module each module can be divided into one or more sub-modules figure different approaches of designing an algorithm top-down approach top-down design approach starts by dividing the complex algorithm into one or more modules these modules can further be decomposed into one or more sub-modulesand this process of decomposition is iterated until the desired level of module complexity is achieved top-down design method is form of stepwise refinement where we begin with the topmost module and incrementally add modules that it calls thereforein top-down approachwe start from an abstract design and then at each stepthis design is refined into more concrete levels until level is reached that requires no further refinement bottom-up approach bottom-up approach is just the reverse of top-down approach in the bottom-up designwe start with designing the most basic or concrete modules and then proceed towards designing higher level modules the higher level modules are implemented by using the operations performed by lower level modules thusin this approach sub-modules are grouped together to form higher level module all the higher level modules are clubbed together to form even higher level modules this process is repeated until the design of the complete algorithm is obtained |
24,272 | data structures using top-down vs bottom-up approach whether the top-down strategy should be followed or bottom-up is question that can be answered depending on the application at hand while top-down approach follows stepwise refinement by decomposing the algorithm into manageable modulesthe bottom-up approach on the other hand defines module and then groups together several modules to form new higher level module top-down approach is highly appreciated for ease in documenting the modulesgeneration of test casesimplementation of codeand debugging howeverit is also criticized because the sub-modules are analysed in isolation without concentrating on their communication with other modules or on reusability of components and little attention is paid to datathereby ignoring the concept of information hiding although the bottom-up approach allows information hiding as it first identifies what has to be encapsulated within module and then provides an abstract interface to define the module' boundaries as seen from the clients but all this is difficult to be done in strict bottom-up strategy some top-down activities need to be performed for this all in alldesign of complex algorithms must not be constrained to proceed according to fixed pattern but should be blend of top-down and bottom-up approaches control structures used in algorithms an algorithm has finite number of steps some steps may involve decision-making and repetition broadly speakingan algorithm may employ one of the following control structures(asequence(bdecisionand (crepetition step input first number as step input second number as step set sum + step print sum step end sequence by sequencewe mean that each step of an algorithm is executed in specified order let us write an algorithm to add two numbers this algorithm performs the steps in purely sequential orderas shown in fig decision decision statements are used when the execution of process depends on the outcome of some condition for exampleif ythen print equal so the general form of if construct can be given asfigure algorithm to add two numbers if condition then process condition in this context is any statement that may evaluate to either true value or false value in the above examplea variable can be either equal to or not equal to howeverit cannot be both true and false if the condition is truethen the process is executed decision statement can also be stated in the following mannerif condition then process else process this form is popularly known as the if-else construct hereif the condition is truethen process is executedelse process is executed figure shows an algorithm to check if two numbers are equal repetition repetitionwhich involves executing one or more steps for number of timescan be implemented using constructs such as whiledo-whileand for loops these loops execute one or more steps until some condition is true figure shows an algorithm that prints the first natural numbers |
24,273 | figure algorithm to test for equality of two numbers figure algorithm to print the first natural of programming examples write an algorithm for swapping two values step input first number as step input second number as step set temp step set step set temp step print ab step end write an algorithm to find the larger of two numbers step input first number as step input second number as step if > print else if < print else print "the numbers are equal[end of if[end of ifstep end write an algorithm to find whether number is even or odd step input number as step if % = print "evenelse print "odd[end of ifstep end write an algorithm to print the grade obtained by student using the following rules step enter the marks obtained as step if > print step if >= and < print step if >= and < print step if >= and < print else print marks grade above - - - less then |
24,274 | data structures using [end of ifstep end write an algorithm to find the sum of first natural numbers step input step set sum step repeat step while < step set sum sum set [end of loopstep print sum step end time and space complexity analysing an algorithm means determining the amount of resources (such as time and memoryneeded to execute it algorithms are generally designed to work with an arbitrary number of inputsso the efficiency or complexity of an algorithm is stated in terms of time and space complexity the time complexity of an algorithm is basically the running time of program as function of the input size similarlythe space complexity of an algorithm is the amount of computer memory that is required during the program execution as function of the input size in other wordsthe number of machine instructions which program executes is called its time complexity this number is primarily dependent on the size of the program' input and the algorithm used generallythe space needed by program depends on the following two partsfixed partit varies from problem to problem it includes the space needed for storing instructionsconstantsvariablesand structured variables (like arrays and structuresvariable partit varies from program to program it includes the space needed for recursion stackand for structured variables that are allocated space dynamically during the runtime of program howeverrunning time requirements are more critical than memory requirements thereforein this sectionwe will concentrate on the running time efficiency of algorithms worst-caseaverage-casebest-caseand amortized time complexity worst-case running time this denotes the behaviour of an algorithm with respect to the worstpossible case of the input instance the worst-case running time of an algorithm is an upper bound on the running time for any input thereforehaving the knowledge of worst-case running time gives us an assurance that the algorithm will never go beyond this time limit average-case running time the average-case running time of an algorithm is an estimate of the running time for an 'averageinput it specifies the expected behaviour of the algorithm when the input is randomly drawn from given distribution average-case running time assumes that all inputs of given size are equally likely best-case running time the term 'best-case performanceis used to analyse an algorithm under optimal conditions for examplethe best case for simple linear search on an array occurs when the desired element is the first in the list howeverwhile developing and choosing an algorithm to solve problemwe hardly base our decision on the best-case performance it is always recommended to improve the average performance and the worst-case performance of an algorithm amortized running time amortized running time refers to the time required to perform sequence of (relatedoperations averaged over all the operations performed amortized analysis guarantees the average performance of each operation in the worst case |
24,275 | time-space trade-off the best algorithm to solve particular problem at hand is no doubt the one that requires less memory space and takes less time to complete its execution but practicallydesigning such an ideal algorithm is not trivial task there can be more than one algorithm to solve particular problem one may require less memory spacewhile the other may require less cpu time to execute thusit is not uncommon to sacrifice one thing for the other hencethere exists time-space trade-off among algorithms soif space is big constraintthen one might choose program that takes less space at the cost of more cpu time on the contraryif time is major constraintthen one might choose program that takes minimum time to execute at the cost of more space expressing time and space complexity the time and space complexity can be expressed using function (nwhere is the input size for given instance of the problem being solved expressing the complexity is required when we want to predict the rate of growth of complexity as the input size of the problem increases there are multiple algorithms that find solution to given problem and we need to find the algorithm that is most efficient the most widely used notation to express this function (nis the big notation it provides the upper bound for the complexity algorithm efficiency if function is linear (without any loops or recursions)the efficiency of that algorithm or the running time of that algorithm can be given as the number of instructions it contains howeverif an algorithm contains loopsthen the efficiency of that algorithm may vary depending on the number of loops and the running time of each loop in the algorithm let us consider different cases in which loops determine the efficiency of an algorithm linear loops to calculate the efficiency of an algorithm that has single loopwe need to first determine the number of times the statements in the loop will be executed this is because the number of iterations is directly proportional to the loop factor greater the loop factormore is the number of iterations for exampleconsider the loop given belowfor( = ; < ; ++statement blockhere is the loop factor we have already said that efficiency is directly proportional to the number of iterations hencethe general formula in the case of linear loops may be given as (nn however calculating efficiency is not as simple as is shown in the above example consider the loop given belowfor( = ; < ; += statement blockherethe number of iterations is half the number of the loop factor sohere the efficiency can be given as (nn/ |
24,276 | data structures using logarithmic loops we have seen that in linear loopsthe loop updation statement either adds or subtracts the loop-controlling variable howeverin logarithmic loopsthe loop-controlling variable is either multiplied or divided during each iteration of the loop for examplelook at the loops given belowfor( = ; < ; *= for( = ; >= ; /= statement blockstatement blockconsider the first for loop in which the loop-controlling variable is multiplied by the loop will be executed only times and not times because in each iteration the value of doubles nowconsider the second loop in which the loop-controlling variable is divided by in this case alsothe loop will be executed times thusthe number of iterations is function of the number by which the loop-controlling variable is divided or multiplied in the examples discussedit is that iswhen the number of iterations can be given by log which is approximately equal to thereforeputting this analysis in general termswe can conclude that the efficiency of loops in which iterations divide or multiply the loop-controlling variables can be given as (nlog nested loops loops that contain loops are known as nested loops in order to analyse nested loopswe need to determine the number of iterations each loop completes the total is then obtained as the product of the number of iterations in the inner loop and the number of iterations in the outer loop in this casewe analyse the efficiency of the algorithm based on whether it is linear logarithmicquadraticor dependent quadratic nested loop linear logarithmic loop consider the following code in which the loop-controlling variable of the inner loop is multiplied after each iteration the number of iterations in the inner loop is log this inner loop is controlled by an outer loop which iterates times thereforeaccording to the formulathe number of iterations for this code can be given as log for( = ; < ; ++for( = < ; *= statement blockin more general termsthe efficiency of such loops can be given as (nn log quadratic loop in quadratic loopthe number of iterations in the inner loop is equal to the number of iterations in the outer loop consider the following code in which the outer loop executes times and for each iteration of the outer loopthe inner loop also executes times thereforethe efficiency here is for( = ; < ; ++for( = < ; ++statement blockthe generalized formula for quadratic loop can be given as (nn dependent quadratic loop in dependent quadratic loopthe number of iterations in the inner loop is dependent on the outer loop consider the code given belowfor( = ; < ; ++for( = <= ; ++statement blockin this codethe inner loop will execute just once in the first iterationtwice in the second iterationthrice in the third iterationso on and so forth in this waythe number of iterations can be calculated as |
24,277 | if we calculate the average of this loop ( / )we will observe that it is equal to the number of iterations in the outer loop ( plus divided by in general termsthe inner loop iterates ( )/ times thereforethe efficiency of such code can be given as (nn ( )/ big notation in today' era of massive advancement in computer technologywe are hardly concerned about the efficiency of algorithms ratherwe are more interested in knowing the generic order of the magnitude of the algorithm if we have two different algorithms to solve the same problem where one algorithm executes in iterations and the other in iterationsthe difference between the two algorithms is not much howeverif the first algorithm executes in iterations and the other in iterationsthen it is matter of concern we have seen that the number of statements executed in the program for elements of the data is function of the number of elementsexpressed as (neven if the expression derived for function is complexa dominant factor in the expression is sufficient to determine the order of the magnitude of the result andhencethe efficiency of the algorithm this factor is the big oand is expressed as (nthe big notationwhere stands for 'order of'is concerned with what happens for very large values of for exampleif sorting algorithm performs operations to sort just elementsthen that algorithm would be described as an ( algorithm when expressing complexity using the big notationconstant multipliers are ignored soan ( nalgorithm is equivalent to ( )which is how it should be written if (nand (nare the functions defined on positive integer number nthen (no( ( )that isf of is big- of of if and only if positive constants and existsuch that (nps cg(nit means that for large amounts of dataf(nwill grow no more than constant factor than (nhenceg provides an upper bound note that here is constant which depends on the following factorsthe programming language usedthe quality of the compiler or interpreterthe cpu speedthe size of the main memory and the access time to itthe knowledge of the programmerand the algorithm itselfwhich may require simple but also time-consuming machine instructions we have seen that the big notation provides strict upper bound for (nthis means that the function (ncan do better but not worse than the specified value big notation is simply written as (no( ( )or as (no( ( )heren is the problem size and ( ( ){ ( )positive constants cn such that < (nn hencewe can say that ( ( )comprises set of all the functions (nthat are less than or equal to cg(nfor all values of > if ( > then (no( ( )and (nis an asymptotically tight upper bound for (nexamples of functions in ( includen |
24,278 | data structures using examples of functions not in ( includen to summarizebest case describes an upper bound for all combinations of input it is possibly lower than the worst case for examplewhen sorting an array the best case is when the array is already correctly sorted worst case describes lower bound for worst case input combinations it is possibly greater than the best case for examplewhen sorting an array the worst case is when the array is sorted in reverse order if we simply write oit means same as worst case table examples of (nand (nnow let us look at some examples of (nand (ntable (nf(no( ( ) shows the relationship between (nand (nnote that ( the constant values will be ignored because the main purpose ( of the big notation is to analyse the algorithm in general ( fashionso the anomalies that appear for small input sizes are ( simply ignored categories of algorithms according to the big notationwe have five different categories of algorithmsconstant time algorithmrunning time complexity given as ( linear time algorithmrunning time complexity given as (nlogarithmic time algorithmrunning time complexity given as (log npolynomial time algorithmrunning time complexity given as (nkwhere exponential time algorithmrunning time complexity given as ( ntable shows the number of operations that would be performd for various values of table number of operations for different functions of ( (log ( ( log ( ( example show that ( solution by definitionwe have < ( <cg(nsubstituting as (nand as ( )we get < <cn dividing by / < / <cn / < / < now to determine the value of cwe see that / is maximum when = thereforec= to determine the value of < / < < / < |
24,279 | < < this means = therefore = example show that ( solution by definitionwe have < ( <cg(nsubstituting as (nand as ( )we get < <cn dividing by / < / / <cn / < / < note that / as and / is maximum when therefore < / < this meansc to determine the value of < / < - < / < - < / < - < / < - < < this implies hence = example show that (nlognsolution by definitionwe have < ( <cg(nsubstituting as (nand nlogn as ( )we get < < log dividing by nlognwe get / log < / log < log nn log < /log < we know that /log as to determine the value of cit is clearly evident that /log is greatest when = therefore < /log < hence to determine the value of we can write < /log < < <log nowlog when hence = example show that ( solution by definitionwe have < ( <cg(nsubstituting as (nand as ( )we get < <cn dividing by / < / / <cn / < / < <( )/ < hence ( |
24,280 | data structures using limitations of big notation there are certain limitations with the big notation of expressing the complexity of algorithms these limitations are as followsmany algorithms are simply too hard to analyse mathematically there may not be sufficient information to calculate the behaviour of the algorithm in the average case big analysis only tells us how the algorithm grows with the size of the problemnot how efficient it isas it does not consider the programming effort it ignores important constants for exampleif one algorithm takes ( time to execute and the other takes ( time to executethen as per big oboth algorithm have equal time complexity in real-time systemsthis may be serious consideration omega notation (othe omega notation provides tight lower bound for (nthis means that the function can never do better than the specified value but it may do worse notation is simply written asf(no( ( ))where is the problem size and ( ( ){ ( )positive constants such that hencewe can say that ( ( )comprises set of all the functions (nthat are greater than or equal to cg(nfor all values of > if cg(non >nothen (no( ( )and (nis an asymptotically tight lower bound for (nexamples of functions in ( includen examples of functions not in ( includenn to summarizebest case describes lower bound for all combinations of input this implies that the function can never get any better than the specified value for examplewhen sorting an array the best case is when the array is already correctly sorted worst case describes lower bound for worst case input combinations it is possibly greater than best case for examplewhen sorting an array the worst case is when the array is sorted in reverse order if we simply write oit means same as best case example show that ( solution by the definitionwe can write <cg( < ( <cn < dividing by / <cn / < / / < < / nowlim + / naetherefore < < hencec now to determine the value of < < / - < < / |
24,281 | - < < / so as lim / naehence ( for = and >no= example show that ( solution by the definitionwe can write <cg( < ( <cn < dividing by we get / <cn / < / < < / thusfrom the above statementwe see that the value of depends on the value of there does not exist value of that satisfies the condition as increases this could fairly be possible if but it is not allowed as the definition by itself says that lim nae theta notation (qtheta notation provides an asymptotically tight bound for (nth notation is simply written asf(nth( ( ))where is the problem size and th( ( ){ ( )positive constants and such that hencewe can say that th( ( )comprises set of all the functions (nthat are between (nand (nfor all values of > if (nis between (nand ( ) > then (nth( ( )and (nis an asymptotically tight bound for (nand (nis amongst (nin the set to summarizethe best case in th notation is not used worst case th describes asymptotic bounds for worst case combination of input values if we simply write thit means same as worst case th example show that / th( solution by the definitionwe can write ( < ( < (nc < / < dividing by we get / < / / < / < / / < this means / because lim / / / (big notationnaeto determine using notationwe can write < / / we see that is minimum when therefore < / / hencec / now let us determine the value of / < / / < / / < / / < / / < / < / |
24,282 | data structures using > you may verify this by substituting the values as shown below < / < / / and / ( < / / < / / < / < / thusin generalwe can write / other useful notations there are other notations like little notation and little notation which have been discussed below little notation this notation provides non-asymptotically tight upper bound for (nto express function using this notationwe write (no( ( )where ( ( ){ (npositive constants cn such that for any and < ( <cg( ) > this is unlike the big notation where we say for some (not anyfor example ( is asymptotically tight upper bound but ( is non-asymptotically tight bound for (nexamples of functions in ( includen log examples of functions not in ( include example show that ( solution by definitionwe have < <cn this is in contradiction with selecting any / an imprecise analogy between the asymptotic comparison of functions (nand (nand the relation between their values can be given asf(no( ( ) ( < (nf(no( ( ) (ng(nf(nth( ( ) (ng(nlittle omega notation (wthis notation provides non-asymptotically tight lower bound for (nit can be simply written asf(no( ( ))where ( ( ){ (npositive constants cn such that for any and this is unlike the notation where we say for some (not anyfor example ( is asymptotically tight upper bound but ( is non-asymptotically tight bound for (nexample of functions in ( ( )includen ( ) ( ) logn ( example of function not in ( ( )is ( (just as example show that / ( solution by definitionwe have <cn / dividing by we get |
24,283 | < / this is contradictory value as for any value of as it cannot be assured to be less than / or / an imprecise analogy between the asymptotic comparison of functions (nand (nand the relation between their values can be given asf(no( ( ) ( > (nf(no( ( ) (ng(npoints to remember data structure is particular way of storing and organizing data either in computer' memory or on the disk storage so that it can be used efficiently there are two types of data structuresprimitive and non-primitive data structures primitive data structures are the fundamental data types which are supported by programming language nonprimitive data structures are those data structures which are created using primitive data structures non-primitive data structures can further be classified into two categorieslinear and non-linear data structures if the elements of data structure are stored in linear or sequential orderthen it is linear data structure howeverif the elements of data structure are not stored in sequential orderthen it is non-linear data structure an array is collection of similar data elements which are stored in consecutive memory locations linked list is linear data structure consisting of group of elements (called nodeswhich together represent sequence stack is last-infirst-out (lifodata structure in which insertion and deletion of elements are done at only one endwhich is known as the top of the stack queue is first-infirst-out (fifodata structure in which the element that is inserted first is the first to be taken out the elements in queue are added at one end called the rear and removed from the other end called the front tree is non-linear data structure which consists of collection of nodes arranged in hierarchical tree structure the simplest form of tree is binary tree binary tree consists of root node and left and right subtreeswhere both sub-trees are also binary trees graph is often viewed as generalization of the tree structurewhere instead of purely parent-to-child relationship between tree nodesany kind of complex relationships can exist between the nodes an abstract data type (adtis the way we look at data structurefocusing on what it does and ignoring how it does its job an algorithm is basically set of instructions that solve problem the time complexity of an algorithm is basically the running time of the program as function of the input size the space complexity of an algorithm is the amount of computer memory required during the program execution as function of the input size the worst-case running time of an algorithm is an upper bound on the running time for any input the average-case running time specifies the expected behaviour of the algorithm when the input is randomly drawn from given distribution amortized analysis guarantees the average performance of each operation in the worst case the efficiency of an algorithm is expressed in terms of the number of elements that has to be processed and the type of the loop that is being used exercises review questions explain the features of good program define the termsdatafilerecordand primary key |
24,284 | data structures using define data structures give some examples in how many ways can you categorize data structuresexplain each of them discuss the applications of data structures write short note on different operations that can be performed on data structures compare linked list with an array write short note on abstract data type explain the different types of data structures also discuss their merits and demerits define an algorithm explain its features with the help of suitable examples explain and compare the approaches for designing an algorithm what is modularizationgive its advantages write brief note on trees as data structure what do you understand by graph explain the criteria that you will keep in mind while choosing an appropriate algorithm to solve particular problem what do you understand by time-space trade-off what do you understand by the efficiency of an algorithm how will you express the time complexity of given algorithm discuss the significance and limitations of the big notation discuss the best caseworst caseaverage caseand amortized time complexity of an algorithm categorize algorithms based on their running time complexity give examples of functions that are in big notation as well as functions that are not in big notation explain the little notation give examples of functions that are in little notation as well as functions that are not in little notation differentiate between big and little notations explain the notation give examples of functions that are in notation as well as functions that are not in notation explain the th notation give examples of functions that are in th notation as well as functions that are not in th notation explain the notation give examples of functions that are in notation as well as functions that are in notation differentiate between big omega and little omega notations show that ( show that + + ( prove that ( show that (lg prove that ( show that / th( multiple-choice questions which data structure is defined as collection of similar data elements(aarrays (blinked lists (ctrees (dgraphs the data structure used in hierarchical data model is (aarray (blinked list (ctree (dgraph in stackinsertion is done at (atop (bfront (crear (dmid the position in queue from which an element is deleted is called as (atop (bfront (crear (dmid which data structure has fixed size(aarrays (blinked lists (ctrees (dgraphs if top max- then that the stack is (aempty (bfull (ccontains some data (dnone of these which among the following is lifo data structure(astacks (blinked lists (cqueues (dgraphs which data structure is used to represent complex relationships between the nodes(aarrays (blinked lists (ctrees (dgraphs examples of linear data structures include (aarrays (bstacks (cqueues (dall of these the running time complexity of linear time algorithm is given as (ao( (bo( (co( log (do( |
24,285 | which notation provides strict upper bound for ( )(aomega notation (bbig notation (csmall notation (dtheta notation which notation comprises set of all functions (nthat are greater than or equal to cg(nfor all values of > (aomega notation (bbig notation (csmall notation (dtheta notation function in ( notation is ( (bn (cn / (dn true or false trees and graphs are the examples of linear data structures queue is fifo data structure trees can represent any kind of complex relationship between the nodes the average-case running time of an algorithm is an upper bound on the running time for any input array is an abstract data type array elements are stored in continuous memory locations the pop operation adds an element to the top of stack graphs have purely parent-to-child relationship between their nodes the worst-case running time of an algorithm is lower bound on the running time for any input in top-down approachwe start with designing the most basic or concrete modules and then proceed towards designing higher-level modules ( ( )comprises set of all functions (nthat are less than or equal to cg(nfor all values of > simply means same as best case small omega notation provides an asymptotically tight bound for ( theta notation provides non-asymptotically tight lower bound for ( ( fill in the blanks is an arrangement of data either in the computer' memory or on the disk storage are used to manipulate the data contained in various data structures in the elements of data structure are stored sequentially of variable specifies the set of values that the variable can take tree is empty if abstract means the time complexity of an algorithm is the running time given as function of analysis guarantees the average performance of each operation in the worst case the elements of an array are referenced by an is used to store the address of the topmost element of stack the operation returns the value of the topmost element of stack an overflow occurs when is fifo data structure the elements in queue are added at and removed from if the elements of data structure are stored sequentiallythen it is is basically set of instructions that solve problem the number of machine instructions that program executes during its execution is called its specifies the expected behaviour of an algorithm when an input is randomly drawn from given distribution the running time complexity of constant time algorithm is given as complex algorithm is often divided into smaller units called design approach starts by dividing the complex algorithm into one or more modules case is when the array is sorted in reverse order notation provides tight lower bound for ( the small notation provides tight upper bound for ( ____ ( |
24,286 | arrays learning objective in this we will discuss arrays an array is user-defined data type that stores related information together all the information stored in an array belongs to the same data type soin this we will learn how arrays are defineddeclaredinitializedand accessed we will also discuss the different operations that can be performed on array elements and the different types of arrays such as two-dimensional arraysmulti-dimensional arraysand sparse matrices introduction we will explain the concept of arrays using an analogy consider situation in which we have students in class and we have been asked to write program that reads and prints the marks of all the students in this programwe will need integer variables with different namesas shown in fig now to read the values of these variableswe must have read statements similarlyto print the value of these variableswe need write statements if it is just matter of variablesthen it might be acceptable for the user to follow this approach but would it be possible to follow this approach if we have to read and print the marks of studentsin the entire course (say studentsin the entire college (say studentsin the entire university (say , studentsthe answer is nodefinitely notto process large amount of datawe need data structure known as array |
24,287 | an array is collection of similar data elements these data elements have the same data type the elements of the array are stored in consecutive memory locations and are referenced by an index (also known as the subscriptthe subscript is an ordinal number which is used to identify an element of the array marks marks marks marks marks marks marks marks marks marks marks marks marks marks marks marks marks marks marks marks figure twenty variables for students declaration of arrays we have already seen that every variable must be declared before it is used the same concept holds true for array variables an array must be declared before being used declaring an array means specifying the followingdata type--the kind of values it can storefor exampleintcharfloatdouble name--to identify the array size--the maximum number of values that the array can hold arrays are declared using the following syntaxtype name[size]the type can be either intfloatdoublecharor any other valid data type the number within brackets indicates the size of the arrayi the maximum number of elements that can be stored in the array for exampleif we writeint marks[ ]then the statement declares marks to be an array containing elements in cthe array index starts from zero the first element will be stored in marks[ ]second element in marks[ ]and so on thereforethe last elementthat is the th elementwill be stored in marks[ note that written within square brackets are the subscripts in the memorythe array will be stored as shown in fig th st nd rd th th th th th th element element element element element element element element element element marks[ marks[ marks[ marks[ marks[ marks[ marks[ marks[ marks[ marks[ figure memory representation of an array of elements figure shows how different types of arrays are declared |
24,288 | data structures using data type [ int marks [ ][ [ [ [ [ [ [ [ [ array name [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ char name [ ]array size [ float salary [ ][ [ [ [ figure declaring arrays of different data types and sizes accessing the elements of an array storing related data items in single array enables the programmers to develop concise and efficient programs but there is no single function that can operate on all the elements of an array to access all the elementswe must use loop that is/set each element of the array to - we can access all the elements of an array by varying the value of the subscript into the array but note that the int imarks[ ]for( ; < ; ++subscript must be an integral value or an expression that marks[ - evaluates to an integral value as shown in fig the first element of the array marks[ can be accessed by figure code to initialize each element of the writing marks[ now to process all the elements of the array to - arraywe use loop as shown in fig figure shows the result of the code shown in fig the code accesses every individual element of the array and sets its value to - in the for loopfirst the value of marks[ is set to - then the value of the index (iis incremented and the next valuethat ismarks[ is set to - the procedure continues until all the elements of the array are set to - - - - - - - - - - - [ [ [ [ [ [ [ [ [ [ figure array marks after executing the code given in fig note there is no single statement that can readaccessor print all the elements of an array to do thiswe have to use loop to execute the same statement with different index values calculating the address of array elements you must be wondering how gets to know where an individual element of an array is located in the memory the answer is that the array name is symbolic reference to the address of the first byte of the array when we use the array namewe are actually referring to the first byte of the array the subscript or the index represents the offset from the beginning of the array to the element being referenced that iswith just the array name and the indexc can calculate the address of any element in the array since an array stores all its data elements in consecutive memory locationsstoring just the base addressthat is the address of the first element in the arrayis sufficient the address of |
24,289 | other data elements can simply be calculated using the base address the formula to perform this calculation isaddress of data elementa[kba(aw( lower_boundherea is the arrayk is the index of the element of which we have to calculate the addressba is the base address of the array aand is the size of one element in memoryfor examplesize of int is example given an array int marks[{ , , , , , , , }calculate the address of marks[ if the base address solution marks[ marks[ marks[ marks[ marks[ marks[ marks[ marks[ we know that storing an integer value requires bytesthereforeits size is bytes marks[ ( ( calculating the length of an array the length of an array is given by the number of elements stored in it the general formula to calculate the length of an array is length upper_bound lower_bound where upper_bound is the index of the last element and lower_bound is the index of the first element in the array example let age[ be an array of integers such that age[ age[ age[ age[ age[ show the memory representation of the array and calculate its length solution the memory representation of the array age[ is given as below ageage[ age[ age[ age[ length upper_bound lower_bound herelower_bound upper_bound thereforelength storing values in arrays when we declare an arraywe are just allocating space for its elementsno values are stored in the array there are three ways to store values in an array firstto initialize the array elements during declarationsecondto input values for individual elements from the keyboardthirdto assign values to individual elements this is shown in fig |
24,290 | data structures using initialize the elements during declaration storing values in an array input values for the elements from the keyboard assign values to individual elements figure storing values in an array initializing arrays during declaration the elements of an array can be initialized at the time of declarationjust as any other variable when an array is initializedwe need to provide value for every element in the array arrays are initialized by writingtype array_name[size]={list of values}marks[ marks[ marks[ marks[ marks[ note that the values are written within curly brackets and every value is separated by comma it is compiler error to specify more values than there are elements in the array when we writeint marks[ ]={ }figure initialization of array marks[ an array with the name marks is declared that has enough space to store five elements the first elementthat ismarks[ is assigned value similarlythe second element of the arraythat is marks[ ]is assigned and so on this is shown in fig while initializing the array at the time of declarationthe programmer may omit the size of the array for exampleint marks[]{ }the above statement is absolutely legal herethe compiler will allocate enough space for all the initialized elements note that if the number of values provided is less than the number of elements in the arraythe un-assigned elements are filled with zeros figure shows the initialization of arrays int marks [ { }int marks [ { }int marks [{ }int marks [ }figure initialization of array elements [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ [ rest of the elements are filled with ' |
24,291 | inputting values from the keyboard an array can be initialized by inputting values from the keyboard in this methoda while/do-while or for loop is executed to input the value for each element of the array for examplelook at the figure code for inputting each code shown in fig element of the array in the codewe start at the index at and input the value for the first element of the array since the array has elementswe must input values for elements whose index varies from to int imarks[ ]for( ; < ; ++scanf("% "&marks[ ])assigning values to individual elements the third way is to assign values to individual elements of the array by using the assignment operator any value that evaluates to the data type as that of the array can be assigned to the individual array element simple assignment statement can be written as marks[ here is assigned to the fourth element of the array which is specified as marks[ note that we cannot assign one array to another arrayeven int iarr [ ]arr [ ]if the two arrays have the same type and size to copy an arrayarr [ , , , , , , , , , }you must copy the value of every element of the first array into for( ; < ; ++the elements of the second array figure illustrates the code arr [iarr [ ]to copy an array in fig the loop accesses each element of the first array figure code to copy an array at the and simultaneously assigns its value to the corresponding individual element level element of the second array the index value is incremented to access the next element in succession thereforewhen this /fill an array with even numbers code is executedarr [ arr [ ]arr [ arr [ ]arr [ int ,arr[ ]arr [ ]and so on for( = ; < ; ++arr[ii* we can also use loop to assign pattern of values to the array elements for exampleif we want to fill an array with figure code for filling an array with even integers (starting from )then we will write the code as even numbers shown in fig in the codewe assign to each element value equal to twice of its indexwhere the index starts from so after executing this codewe will have arr[ arr[ arr[ and so on operations on arrays there are number of operations that can be preformed on arrays these operations includetraversing an array inserting an element in an array searching an element in an array deleting an element from an array merging two arrays sorting an array in ascending or descending order we will discuss all these operations in detail in this sectionexcept searching and sortingwhich will be discussed in traversing an array traversing an array means accessing each and every element of the array for specific purpose |
24,292 | data structures using traversing the data elements of an array can include printing every elementcounting the total number of elementsor performing any process on these elements sincearray is linear data structure (because all its elements form sequence)traversing its elements is very simple and straightforward the algorithm for array traversal is given in fig step [initializationset lower_bound step repeat steps to while <upper_bound step apply process to [istep set [end of loopstep exit figure algorithm for array traversal in step we initialize the index to the lower bound of the array in step while loop is executed step processes the individual array element as specified by the array name and index value step increments the index value so that the next array element could be processed the while loop in step is executed until all the elements in the array are processedi until is less than or equal to the upper bound of the array programming examples write program to read and display numbers using an array #include #include int main(int inarr[ ]clrscr()printf("\ enter the number of elements in the array ")scanf("% "& )for( = ; < ; ++printf("\ arr[% " )scanf("% ",&arr[ ])printf("\ the array elements are ")for( = ; < ; ++printf("\ % "arr[ ])return output enter the number of elements in the array arr[ arr[ arr[ arr[ arr[ the array elements are write program to find the mean of numbers using arrays #include #include int main( |
24,293 | int inarr[ ]sum = float mean clrscr()printf("\ enter the number of elements in the array ")scanf("% "& )for( = ; < ; ++printf("\ arr[% " )scanf("% ",&arr[ ])for( = ; < ; ++sum +arr[ ]mean (float)sum/nprintf("\ the sum of the array elements % "sum)printf("\ the mean of the array elements "mean)return output enter the number of elements in the array arr[ arr[ arr[ arr[ arr[ the sum of the array elements the mean of the array elements write program to print the position of the smallest number of numbers using arrays #include #include int main(int inarr[ ]smallposclrscr()printf("\ enter the number of elements in the array ")scanf("% "& )printf("\ enter the elements ")for( = ; < ; ++scanf("% ",&arr[ ])small arr[ pos = for( = ; < ; ++if(arr[ ]<smallsmall arr[ ]pos iprintf("\ the smallest element is % "small)printf("\ the position of the smallest element in the array is % "pos)return output enter the number of elements in the array enter the elements |
24,294 | data structures using the smallest element is the position of the smallest element in the array is write program to find the second largest of numbers using an array #include #include int main(int inarr[ ]largesecond_largeclrscr()printf("\ enter the number of elements in the array ")scanf("% "& )printf("\ enter the elements")for( = ; < ; ++scanf("% ",&arr[ ])large arr[ ]for( = ; < ; ++if(arr[ ]>largelarge arr[ ]second_large arr[ ]for( = ; < ; ++if(arr[ !largeif(arr[ ]>second_largesecond_large arr[ ]printf("\ the numbers you entered are ")for( = ; < ; ++printf("\ % "arr[ ])printf("\ the largest of these numbers is % ",large)printf("\ the second largest of these numbers is % ",second_large)return output enter the number of elements in the array enter the elements the numbers you entered are the largest of these numbers is the second largest of these numbers is write program to enter number of digits form number using these digits #include #include #include int main(int number= digit[ ]numofdigits,iclrscr()printf("\ enter the number of digits ")scanf("% "&numofdigits)for( = ; <numofdigits; ++printf("\ enter the digit at position % " + ) |
24,295 | scanf("% "&digit[ ]) = while( <numofdigitsnumber number digit[ipow( , ) ++printf("\ the number is % "number)return output enter the number of digits enter the digit at position enter the digit at position enter the digit at position enter the digit at position the number is write program to find whether the array of integers contains duplicate number #include #include int main(int array[ ]injflag = clrscr()printf("\ enter the size of the array ")scanf("% "& )for( = ; < ; ++printf("\ array[% " )scanf("% "&array[ ])for( = ; < ; ++for( = + ; < ; ++if(array[ =array[ & !=jflag = printf("\ duplicate numbers found at locations % and % "ij)if(flag== printf("\ no duplicates found")return output enter the size of the array array[ array[ array[ array[ array[ duplicate numbers found at locations and |
24,296 | data structures using inserting an element in an array if an element has to be inserted at the end of an existing arraythen the task of insertion is quite simple we just have to add to the upper_ figure algorithm to append new element to an bound and assign the value herewe assume that existing array the memory space allocated for the array is still available for exampleif an array is declared to contain elementsbut currently it has only elementsthen obviously there is space to accommodate two more elements but if it already has elementsthen we will not be able to add another element to it figure shows an algorithm to insert new element to the end of an array in step we increment the value of the upper_bound in step the new value is stored at the position pointed by the upper_bound for examplelet us assume an array has been declared as step set upper_bound upper_bound step set [upper_boundval step exit int marks[ ]the array is declared to store the marks of all the students in class nowsuppose there are students and new student comes and is asked to take the same test the marks of this new student would be stored in marks[ assuming that the student secured markswe will assign the value as marks[ howeverif we have to insert an element in the middle of the arraythen this is not trivial task on an averagewe might have to move as much as half of the elements from their positions in order to accommodate space for the new element for exampleconsider an array whose elements are arranged in ascending order nowif new element has to be addedit will have to be added probably somewhere in the middle of the array to do thiswe must first find the location where the new element will be inserted and then move all the elements (that have value greater than that of the new elementone position to the right so that space can be created to store the new value example valuesdata[is an array that is declared as int data[ ]and contains the following data[{ }(acalculate the length of the array (bfind the upper_bound and lower_bound (cshow the memory representation of the array (dif new data element with the value has to be insertedfind its position (einsert new data element and show the memory representation after the insertion solution (alength of the array number of elements thereforelength of the array (bby defaultlower_bound and upper_bound ( datadata[ data[ data[ data[ data[ data[ data[ data[ data[ (dsince the elements of the array are stored in ascending orderthe new data element will be stored after at the th location soall the array elements from the th position will be moved one position towards the right to accommodate the new value |
24,297 | ( datadata[ data[ data[ data[ data[ data[ data[ data[ data[ data[ algorithm to insert an element in the middle of an array the algorithm insert will be declared as insert (anposvalthe arguments are (aathe array in which the element has to be inserted (bnthe number of elements in the array (cposthe position at which the element has to be inserted (dvalthe value that has to be inserted in the algorithm given in fig in step we step [initializationset first initialize with the total number of elements step repeat steps and while >pos in the array in step while loop is executed step set [ [iwhich will move all the elements having an index step set [end of loopgreater than pos one position towards right to create step set space for the new element in step we increment step set [posval the total number of elements in the array by and step exit finally in step the new value is inserted at the desired position figure algorithm to insert an element in the middle of an array nowlet us visualize this algorithm by taking an example initial data[is given as below datadata[ data[ data[ data[ data[ calling insert (data will lead to the following processing in the array datadata[ data[ data[ data[ data[ data[ datadata[ data[ data[ data[ data[ data[ datadata[ data[ data[ data[ data[ data[ datadata[ data[ data[ data[ data[ data[ programming examples write program to insert number at given location in an array #include |
24,298 | data structures using #include int main(int innumposarr[ ]clrscr()printf("\ enter the number of elements in the array ")scanf("% "& )for( = ; < ; ++printf("\ arr[% " )scanf("% "&arr[ ])printf("\ enter the number to be inserted ")scanf("% "&num)printf("\ enter the position at which the number has to be added ")scanf("% "&pos)for( = - ; >=pos; --arr[ + arr[ ]arr[posnumn + printf("\ the array after insertion of % is "num)for( = ; < ; ++printf("\ arr[% % "iarr[ ])getch()return output enter the number of elements in the array arr[ arr[ arr[ arr[ arr[ enter the number to be inserted enter the position at which the number has to be added the array after insertion of is arr[ arr[ arr[ arr[ arr[ arr[ write program to insert number in an array that is already sorted in ascending order #include #include int main(int injnumarr[ ]clrscr()printf("\ enter the number of elements in the array ")scanf("% "& )for( = ; < ; ++printf("\ arr[% " )scanf("% "&arr[ ])printf("\ enter the number to be inserted ") |
24,299 | scanf("% "&num)for( = ; < ; ++if(arr[inumfor( - >=ij--arr[ + arr[ ]arr[inumbreakn + printf("\ the array after insertion of % is "num)for( = ; < ; ++printf("\ arr[% % "iarr[ ])getch()return output enter the number of elements in the array arr[ arr[ arr[ arr[ arr[ enter the number to be inserted the array after insertion of is arr[ arr[ arr[ arr[ arr[ arr[ deleting an element from an array deleting an element from an array means removing data element from an already existing array if the element has to be deleted from the end of the existing arraythen the task of deletion is quite simple we just have to subtract from the upper_bound figure shows an algorithm to delete an element from the end of an array for exampleif we have an array that is declared as int marks[ ]the array is declared to store the marks of all the students in the class nowsuppose there are students and the student with roll number leaves the course the score of this student was stored in marks[ we just have to decrement the upper_bound subtracting from the upper_bound will indicate that there are valid data in the array howeverif we have to delete an element from the middle of an arraythen it is not trivial task on an averagewe might have to move as much as half of the elements from their positions in order to step set upper_bound upper_bound occupy the space of the deleted element step exit for exampleconsider an array whose elements are arranged in ascending order nowsuppose an element figure algorithm to delete the last element of has to be deletedprobably from somewhere in the an array |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.