0% found this document useful (0 votes)
264 views76 pages

FDS 80

Uploaded by

abhijit auti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
264 views76 pages

FDS 80

Uploaded by

abhijit auti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 76
easy - solutions SPPU Fundamentals of Data Structures WF Techknowtedge {MI Fundamentals of Data Structures (Semester Ill - Information Technology) (SPPU) Copyright © with Techknowledge Publications. All rights reserved. No part of this publication may be reproduced, copied, or stored in a retrieval system, distributed or transmitted in any form or by any means, including photocopy, recording, ot other electronic or mechanical methods, without the prior written permission ofthe publisher. ‘This book is sold subject to the condition that it shall not, by the way of trade or otherwise, be lent, resold, hired out, or otherwise circulated without the publisher's prior written consent in any form of binding or cover other than which itis published and without a similar condition including this condition being imposed on the subsequent purchaser and ‘without limiting the tights under copyright reserved above. Edition 2019 This edition is for sale in India, Bangladesh, Bhutan, Maldives, Nepal, Pakistan, Sri Lanka and designated countries in South-East Asia. Sale and purchase of this book outside of these countries is unauthorized by the publisher. Printed at : 37/2, Ashtvinayak Industrial Estate, Near Pari Company, athe, Pune, Maharashtra State India, Pune ~ 411041 Published by ‘TechKnowledge Publications Head Office : B/S, First floor, Maniratna Complex, Taware Colony, Aranyeshwar Comer, Pune -411 009. Maharashtra State, India Ph : 91-20-24221234, 91-20-24225678, Email :[email protected], Website : www-techknowledgebooks.com Code : EPO22A) Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 : Chapter 11 : Index Syllabus Dec. 2016 May 2017 Dec. 2017 May 2018, INDEX An Overview of C Language Operators and Expressions in ‘C’ Control Flow in ‘C’ Arrays, Structure and Union Pointers File Handling in C Recursion Introduction to Data Structures and Analysis of Algorithm Searching and Sorting Linear Data Structures using Sequential Organization Linear Data Structures using Linked Organization Table of Contents FDS-01 to FDS -08 FDS -08 to FDS -14 FDS -14 to FDS -26 FDS -26 to FDS -36 University Question Papers FDS -36 to FDS -38 FDS -01 to FDS -21 Dec. 2018 May 2019 FDS -21 to FDS -31 University Question Papers Q-01 to Q-02 SYLLABUS CER Ri Control structures, arrays, functions and parameter passing Structure and Union, String manipulation, ‘matrix operations. Unit 11: Pointers in C and File Handling Introduction to Pointers, dynamic memory allocation, pointer to pointer, pointer to single anid multidimensional arrays, array of pointers, string and structure manipulation using pointers, pointer to functions. Pointer to file structure and basic ‘operations on file, file handling in C. Unit III: Introduction to Data Structures and Analysis of Algorithms Introduction to Data-Structures: Concept of data, Data object, Data structure, Abstract Data Types, realization of ADT in 'C. Concept of Primitive and non-primitive, linear and Non-linear, static and dynamic, persistent and ephemeral data structures. Analysis of algorithm: frequency count and its importance in analysis of an algorithm, Time complexity & Space ‘complexity of an algorithm, Big ‘0’, ‘A and '@' notations, Best, Worst and Average case analysis ofan algorithm, Unit IV : Searching And Sorting Techniques ‘Need of searching and sorting, Concept of internal and external sorting, sort stability. Searching methods: Linear and binary search algorithms their comparison and complexity analysis Sorting methods: Bubble, selection, insertion, merge, quick, bucket sort and their time and space complexity analysis. Unit V : Linear Data Structures Using Sequential Organization Concept of sequential organization, Concept of Linear data structures, Concept of ordered list, Multidimensional arrays and their storage representation: row major and column major form and address calculation, Representation of sparse ‘matrix using arrays, algorithms for sparse matrix addition, simple and fast transpose, polynomial representation using arrays. Analysis of these algorithms. Introduction to Stack and Queue, and their implementation using sequential organization, use of stack in recursion. Unit VI: Linear Data Structures Using Linked Organization Concept of linked organization, singly linked list, doubly linked list, circular linked list. Linked list as an ADT. Representation and manipulations of polynomials using linked lists, comparison of a sequential and linked memory ‘organization, concept of Generalized Linked List, representation polynomial using GLL. | ‘Chapter 1 oe Marks | o2Marks | ~ = Chapter 2 5 ~_| 04 Marks | 03 Marks Chapter 3 =| 08 Marks | 08 Marks | 03 Marks Chapter 4 Marks | =| 08 Marks Chapter 5 12Marks | 07 Marks | 08 Marks [17 Marks ‘Chapter 6 =| 07 Marks | 04 Marks | 12 Marks (Chapter 7, os Marks | - | O4Marks [= Chapter 8 te Marks | 11 Marks | 12 Marks | 13 Marks Chapter 9 14Marks | 12 Marks | 12 Marks | 12 Marks ‘Chapter 10 18 Marks | 27 Marks | 28 Marks [11 Marks Chapter 11 26 Marks [ 26 Marks | 24 Marks | 13 Marks Repeated Questions : zi = = Chapter 1 : An Overview of C Language [Total Marks : 08] Explain entry controlled loop structures in C, (4 Marks) ‘Ans. : Explain entry controled loop structures a. 1a) Fig. fe 1a) ‘An entry control loop checks the condition at the time of entry and if condition or expression becomes true then control transfers into the body of the loop. Such type of loop controls entry to the loop that’s why its called entry contro loop. Example: ‘The while loop isthe simplest looping structure. Its of entry control looping structure. If we have to execute some statements repeatedly as long ascertain condition become true we can use the ‘hile loop. Inthe while loop the given expression will be check at the time of the loop entry, if given expression becomes true then control will transfer into the loop body. ‘The statement inside the loop body will be executed. The counter value will be modified and again given expression will be checked to enter into the loop. This process will continue until the given expression become false. The while loop contains only ‘expression part, initialization will be done before the while loop — What are advantages of using structure ? Give difference between union and structure, (4 Marks) Ans. : Following are the advantages of using structure : 1, Its used to represent multiple data items of same type by using only single name. 2. It can be used to implement other data structures like linked lists, stacks, queues, tees, graphs et. 3. 2Darmays are used to represent matrices 4. Ibis very simple to represent the real life entities using structures. Difference between Structure and Union : Structure Union Keyword | The Keyword struct is | The Keyword union is used to define a | used to define a union structure Size When a variable is | When a variable is associated with a | associated with a structure, the complier | union, the complier allocates the memory | allocates the memory WF Fundamental of Data Stuctures(SPPU r0s2 Structure Union Tor each member. The | by considering the size size of structure is | of the largest memory. greater than or equal to | So, size of union is the sum of sizes ofits | equal to the size of members largest member. ‘Memory | Each member within a | Memory allocated is structure is assiened | shared by individual ‘unique storage area of | members of union location. Value | Altering the value of | Altering the value of atesing | a member will not | any of the member will, affed other me | alter other member members of the | values structure. ‘Accessing | Individual member can | Only one member can members | be accessed at atime. _| be accessed at a time. Tnitializa | Several members of « | Only the first member on of| structure can initialize | of a union can be members | at once intiialized. Chapter 4 : Arrays, Structure and Union [Total Marks :04] @.2(6) Explain concept of arrays with suitable example. (4 Marks) ‘Ans, :Array is a data stiucture that stores similar elements sequentially. Iti a collection of same elements stored sequentially. tet ment | | ‘umberdot | wmberttl | wumbersa} | nombenist | — Fig. 2-0. 26) ‘They ate the contiguous blocks of memory ae declared as follows: 5 : Pointers [Total Q.1(c) What Is pointer variable ? Explain declaration, Initialization and accessing a pointer variable with an example. (4 Marks) Ans. : In C there is special type of variables that stores the address of another variable. Such a variable is called asa Pointer variable. Hence, it is simply a variable that stores the address of another variabe, Declaring pointer variable: Data_type* var_name; Bg: in *pt; “Hence, p is a pointer variable of type int which means that ptr is capable of storing an address of any integer variable. ‘Consider the following code which shows use of pointer variable. ‘@.2(@) Write pseudo C algorithm for reverse of string using pointers. (4 Marks) Ans. : Peuedo C Algorithm using Pointers for String Reversal.Void string reverse(char* s1, char*s2) @.2(@) Explain call by value and call by reference functions with suitable example. (4 Marks) ‘Ans, : Call by value and call by reference ‘There are two ways to pass argumentsparameter to funtion calls ~ call by value and call by reference. In call by value a copy of actual arguments is passed to respective fomal arguments. Tt usually leads to more compact programs with fewer extraneous variables, because parameters can be treated as conveniently initialized local variables in the called routine. ‘While, in call by reference the location (address) of actual arguments is passed o formal arguments, hence any change made to formal arguments will also reflect in actual arguments. “There are some cases where we need cal by reference: 1 The called function communicates to the calling function only though return statement and return statement can only send only one value back tothe calling function. If there ae ‘more than one value we want to alter, call by reference required 2, Ifthe size of data is large , copying actual arguments to formal arguments could be atime consuming operation and ‘occupies more memory. Aun WF Fundamentals of Data Structures (SPPU) FDS. Example Call by’ Example Call by Reference: Chapter 7 : Recursion [Total Marks : 06] Stack is a data structure that works on Last In First out principle. Stack can store any items but the access of the elements is strictly | {followed using LIFO principle. Push operation ls used to insert the element into the stack. Stack has a pointer called top. This pointer always points to the last element inserted in the stack. Whenever push() Is called the eloment is inserted at location by incrementing top. Also, whenever the element is removed, the element is removed from the top end itself. (6 Marks) 2. 6(@) {top=top-; increment top to point to next empty location aftop]=x; element is inserted at the top of stack ) Pop is an operation that deletes the top element from the stack and returns it. Chapter 8 : Introduction to Data Structures \d Analysis of Algorithm [Total Marks : 12] . 3(a)_ Define the following terms with example (Data object (ii) Data structure Ail Abetract datatype. (6 Marka) Ans. : Data Object : ‘A data object i a region of storage tht contains a value ot soup of values. Each value canbe accessed using its identifier ora ‘more complex expression tat refers to the objec. In addition, each object has a unigue data type. The data type of an object determines the. storage allocation for that object and the interpretation ofthe values during subsequent acces. Data Structure : It is defined asa systematic way of organising and storing data for efficient eroval. It canbe classified a (@) Built in datatypes : For these data types, the programming languages have built in suppor. For Eg. Int, fot, Boolean ec. (0) Derived data types ‘These are the data types derived from the builtin data types For. Bg Lis, Array, Queue, Stack ete Abstract Data Type : ‘An abstract datatype (ADT) is basically a logical description ra spcification of components ofthe data and the operations that ‘a allowed, that is independent ofthe implementation, ADT area theoretical concept in computer science, used in the design and analysis of algorithms, data structures, and software systems, and do not correspond to specific features of computer languages, @.4(@) Explain Big-oh, omega and theta notation with ‘example. (6 Marke) ‘Ans. : Notation ‘The function f(x) is suid tbe O(g(x) (pronounced as big — ot if there exist two positive integevteal number constants C and such that £(9) $CgG forallx2K Example iff )=20 43841 then fx) $6x° forall x2 1 #2843041 = OG) as (8) $C. x° for all x2 K where C= 6 and K= 1 ‘The notation O provides asymptotic upper bound for a given function. The purpose ofthe asymptotic growth rate notations and functions denoted by them is to facilitate the recognition of essential character of a complexity funeion though some simpler funtion @eomnI W Fundamentals of Data Structures (SPU) FDS-4 ‘Q Notation ‘This provides asymptotic lower bound fora given function. A function f(x) is said to be @ (g(x) (Pronounced as big-omega) if there exist two positive integer/eal number constants C and K such that fx) 2 C (g(a) whenever x2 K Example iff) 220 +301 then 3) 2x forall x21, C=1 2x 43x HQ) Notation 0 This provides simultaneously both asymptotic upper bound and asymptotic lower bound fra given function. A function fx) is Said to be © (g(0) (Gronounced big theta) if, there exist postive constats C,,C, and K such that C, g(x) $ f(x) $C, 268) for all x2 K. For any two functions fx) and g(x), fx) = 8 (g(8) and only iff) = OC) and fx) = 2 (gts) Chapter 9 : Searching and Sorting [Total Marks : 14) .3(b) Write pseudo C algorithms for : (Linear search (i) Binary search. (7 Marks) ‘Ans. Linear Search : for(int isQcien; i++) mis the Tength of the array in which numbers are stored Binary Search = aon (b) Explain selection sort with given example by showing all passes. Also analyze time complexity. Number are : 17, 35, 24, 13, 26, 14. (7 Marks) ‘Ans. : Selection sort ‘Selection sort is a comparison type of sorting where the elements are compared. he selection sort algorithm sorts an array by repeatedly finding the minimum element (consideting ascending ford) from unsorted part and putting it at the beginning. The algorithm mntains two subarrays in a given array. The one which is sorted and the other which is unsorted.In every iteration of selection sor, the minimum element from the unsorted subarry is, picked and moved tothe sorted subarray. void selectionSort(int ar], int a) 17,35,24,13,26.14 A the end of First Pass: Find the min element in arr{0..6} and place it at beginning 17 finds 13 lesser than it hence gets swapped with it 13,3524,17,26.14 [Atthe end of Second Pass Find the min element in ar{.6] and place it at beginning 135 gots swapped with 14 ¥ Fundamentals of Data Structures (SPPU) FDS-5 13,18,24,17,26.35 At the end Third Pass Find the min element in ar(2.5) and place it a beginning 24 gets swapped with 17 13,14,17,2426,35 ‘At the end of Fourth Pass Find the min element in ar{3.5) and place it at beginning 13,14,17,24,2635 At the end of Fifth Pas: Find the min element in are(3.5] and place it at beginning 13,14,17,24,26,35 At the end of sixth Pass: Find the min element in ar(4.5] and place it at beginning 13,14,17,2426,35 Analyzing Selection Sort Algorithm: ‘The total running time for selection sort has tree pars ‘The running time forall the calls to find minimum index. ‘The running time forall the calls to swap. ‘The running time forthe rest ofthe loop in the selection Sort function. ‘The time for all calls to swap is \Theta(n)®(n). The running time forall the calls to find minimum index is @(n'), The loop in index Of Minimom will always maken? + 1/2, iterations, regardless of the input. Therefore, we can say that selection sort runs in @(n4 time in all cases. Chapter 10 : Linear Data Structures using ‘Sequential Organization [Total Marks :18] Q.5(@) Write a pseudo C algorithm for addition of two sparse matrices. Analyze its time complexity. (6 Marks) Ans. : Input itn n ENTER the elements of a(n)(a} and b{n}{a) matrix. Also declare matrix fafa}. for i=0 ton) for(j=0 to n) accept alii} and bill PRINT a and b matrix in matrix form, ‘SET a loop up to ow and inner loop up to column. ADD the clements of a and b in column wise and store the value the ‘Terminate the program. Both the inner and outer for loop execute for times and hence, the time complexity of the algorithm is O(a). @.5(6) Explain the two-dimensional array In detail with column and row major representation and ‘address calculation in both the cases. (6 Marks) oTeass-sotutiens) ‘Ans. ‘Two-dimensional array Row Major : elements of array store in contiguous memory locations ow by row: Column Major: elements of array store in contiguous ‘memory locations column by column, sie sori wa : "| 932 Row major Representation will be: 518,647.92 Column major Representation wil be: 569,143.72. 1 figure there is 3x3 array and memory location start from 200 and each element take 2 addres. We can calculate element at ‘Amay(3J1] for both row and column major as follows here m= 3 T= 3i) Formula for row major AvraylG] = Base+w( ne @I)) = 200+2(3(3-1)+(1-1)) = 22 Formula for column major ‘Avsay{i]G) = Base+w( m(-1)2G:))" z = 200+2G(-1)4+(3-1)) ~ = 204 a - st e Address Calculation in single (one) Dimension Array: Momory epace acquiod by ovary elements nthe 1, w= 2, base address = 200 Actual Address ofthe 1” ‘lem of tha aay is know a ‘ray is calles ‘Base Address (2) wath ow Hare ile 1100 Hore itis 4 bytes J AA 1100] 1104] s108 | 2912 | 1116 | 1120 7 Resval accross | __intse meme Elements wir jan 93 | 20 | Aadress with respect Mmaray Gubecrm) | 9] t/] 2] 3] 4] 5 Lower umBound ‘of Suber 8) Fig. 1-0.5() ‘Array of an element of an array say “A[ I J” is caloulated using the following formula: Address of A[1]=B+W*(1-LB) Where, B = Base address W. = Storage Size of one element stored in the array (inbyte) I = Subscript of element whose address isto be found LB = Lower limit / Lower Bound of subserip,ifnot specified assume 0 (zero) Example: Givven the base address of an array B[1300....1900] as 1020 and size ofeach element is 2 bytes in the memory. Find the address ‘of B(1700}, ‘The given values are: B = 1020, L 300, W = 2,1= 1700 Fundamentals of Data Structures (SPPU) FDS-6 ‘Address of A (I] =B + W *(1-LB) 1020 +2 * (1700 - 1300) 1020+2* 400 1020 +800 = 1820 ‘Two - Dimensional Array: ‘A two dimensional Array A is the collection of 'm X a clements. ing language stores the two dimensional array {in one dimensional memory in either of two ways - 1) _ Row Major Order: First row of the array occupies the first set of memory locations reserved for the array; Second row occupies the next set, and so forth. To determine element address Afi, Location (A[ij]) = Base Address + (Nx(I-1))+(j-1) For example : Given an array [I...5,1...7]of integers. Calculate address of ‘element T[4,6], where BA=900. Solution : NeT BA+(7x(4-1)) +61) = 900K x3) 45 = 900421 +5 =926 2) Column Major Order: ‘Order elements of frst column stored linearly and then comes clements of next column. ‘To determine element address Aff]: Location (ALj]) = Buse Address (Mx (j-1))+(i-1) | For example : Given an atray (1...61...8] of integers, Calculate address ‘element T(5,7], where BA=300. Solution = I = 5,1=7,.M=6,N=8 Location (T[S6) = BA+(6x(7-1))+G-1) = 3004 6x6) +4 300+ 3644 = 340 @.(b) Explain polynomial representation of an array and also write data structure declaration with ‘Suitable example. (6 Marks) ‘Ans. : Polynomial representation of an array ‘Representation of a Polynomial: A polynomial is an ‘expression that contains more than two terms. A term is made up ‘of coefficient and exponent. An example of polynomial is Pox) = ax's6x44 7x49 Array representation assumes thatthe exponents ofthe given expression are arranged from 0 to the highest value (degree), which {is represented by the subscript ofthe array beginning with 0. The coefficients of the respective exponent are placed at an appropriate index in the array. The array representation for the above ‘polynomial expression is given below : aw o7e4 (coefficients) o123 (exponents) Hence, for the array representation, we an define a simple array of required array size. int a3, AA structure can be used to declare the polynomials using more efficient way for dynamic allocation. Chapter 11 : Linear Data Structures using Linked Organization [Total Marks : 26] @.7() Explain concept of generalized linked list and representation polynomial using GLL given example : 4x’ + 2x + Gxy + 7xy.. (6 Marks) ‘Ans. : Generalized linked list, "A generalized linked lst contains structures or elements with ‘every one containing its own pointer. Its generalized if the lst can have any deletions, insertions, and similar inserted effectively into it, “Thus, the given expression can be stored as 43° 0 NEXT 202 0 NEXT 6 1 1 NEXT 7 10 3) NULL ‘G.7() Wille © function to Insert @ node and delete nodeln DLL. (7 Marks) ‘Ans. : Insert a node and delete a node in DLL aun Fundamentals of Data Structures (SPPU) FDS7 “C* function for inserting a number atthe rear of a circular linked list. ‘© ttarpuoness roe Fig. 2-Q.8(a) : Insertion of a node at rear in circular linked list “C’ function for inserting a number atthe front of the circular inked list. @.8(a) Explain with suitable example: (6 Marks) () Circular linked list (il) Linked tist as an ADT. Ans. : (Circular linked tist In a circular linked list, last node is connected back tothe first ‘node. In some applications, itis convenient to use circular Linked list. A queue data structure can be implemented using a circular linked list, with a single pointer “rear” as the front node can be | tccrved ough he ear node, ' Rear | ooo Er | Feros Insertion of a node atthe start or end of a circular linked list ‘identified by a pointer to the last node of the linked list takes a constant amount of time, It is iespective of the length of the linked list. Algorithm for traversing a circular list is slightly different than the same algorithm fora singly connected inked list because “NULL” is not encountered, Gem WF Fundamentals of Data Stuctures(SPPU) FDS-8 ae Fundamentals of Date SHUCtUteS (SPP function fo pini(node * Fear) a circular linked NULL) © Ps wear next: [sta esi t$) prinl(nted”, P+ daa P= Pent +} while(P ! = rear > next); + a Tn a circular linked list, starting and the terminating case for traversal are same, In such a case, do-while ig the most suitable construct for traversing, ii) Linked list as an ADT [ADT iin the above content refers tothe structure ofthe node ‘and the various functions associated with the linked list. Body of the functions is not provided as they are discussed in the subsequent sections. The datatype is assumed tobe integer type. Structure ‘ype strat node «ink data; | struct node *nexts Fades Functions: node "ereateg: oid priat(node int count (node foumber of nodes © ode # reverse weds eo = _ node * insert (node * into, int dats) ‘poanare * Delete (nde *, in: de Search (awl; tt), void sort (node (6) Write a pseudo © algorithm to merge two sorted linked lists into the third, (7 Marks) Ans. Psuedo C Code to merge the 2 link lists (Rede 11,12; f'two link Lists w6 be merged, ‘loop through ll the noes and copy i ‘WhiteQ1-> new! =NUEL) po. Be>next=ll-> nests ; i Be data=11-> data; Be next=12; instead of pointing lst noe to NULL point it towards the head ofthe second link ist so thatthe two lnk lists get merged. ‘Ms the merged ink is. Chapter 1: An Overview of C Language [Total Marks : 02] Q4(@) What is use of void datatype? (2 Marks) ‘Ans, : Use of void data type “The data type void actually refers to an object that does not havi a value of any type. We have already seen examples ofits use ‘when we have defined functions that retum no value, i. functions ‘which only print a message and have no value to return. Such a function is used for its side effect and not for its value. In the function declaration and definition, we have indicated that the function does not reurn a value by using the data type void to show an empty type, i. no value. Similarly, when a function has ‘no formal parameters, the keyword void is used in the function [prototype and header to signify that there is no information passed to the function. Chapter 3: Control Flow in [Total Marks : 08] @.1(b) What Is macro 2 compare it with function. (4 Marks) ‘Ans. : Macro ‘Macros are pre-processed which means that all the macros ‘would be processed before your program compiles. However, functions are not pre-processed but compiled Sr. ba Macro Function 1_| Macro is pre-processed Function is compiled 2 No type checking “Type checking is done 3. | Code length increases ‘Code length remains %,_| Use of macro can lead to side | No side effect cffect Speed of execution is faster | Speed of execution is slower % | Before compilation macro | During function call, name Is replaced by muwtv | uansfer of control takes vale place 7. | Useful where small code | Useful where large code appears many time appears many time %. | Generally macros_do not | Function can be of any extend beyond one line numberof ines 9, | Macro does not check | Function checks compile compiler errors errors Q..2(a) Explain different storage classes in C. (4 Marks) ‘Ans. Storage classes in C 'A storage class defines the scope (visibility) and lifetime of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C rogram auto register static auto aon WF Fundamentals f Data Sictues (SPU) rose ‘The auto storage class is the default storage class forall local variables. i ‘The example above defines two variables within the storage class. ‘auto’ can only be used within functions, ie. local variables. register ‘The register storage class is used to define local variables that should be stored in a register instead of RAM. This means thatthe variable has a maximum size equal to the register size (usually one word) and can't have the unary '& operator applied to it as it does, ‘not have a memory location). The register should only be used for variables that require quick acess such as counters. It should also be noted that defining ‘egister’ does not mean thatthe variable will be stored ina register. static static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to ‘maintain their values between function calls extern ‘The extem storage class i used to give a reference of a global variable that i visible to ALL the program files. When you use ‘exter, the variable cannot be initialized however, it points the variable name at a storage location that has been previously efined. When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function, Just for understanding, exter is used to declare a global variable or function in another file. Chapter 5 : Pointers [Total Marks : 07] @.1(c) Explain the use of pointer to array of structure with suitable example. (2 Marks ‘Ans. : Use of pointer to array of structurePointer to aray of structure stores the base address ofthe aay. The pointer stores the base address and with each index you can access every element of| @.2(b) What is pointer ? Explain pointer to a function with suitable example. (6 Marks) ‘Ans. : Pointer A pointer is a variable that i capable of storing the address of, ‘another variable. In C, it is also possible to define and use function pointers, ie. pointer variables which point to functions. Function pointers'can be declared, assigned values and then used to access the functions they point to, Function pointers are declared as follows: int (0s, double (*fpu0;, ‘We can assign values to function pointer variables by making use of the fact that, in C, the name of function, used in an expression by itself, is a pointer to that function. For example, if ‘square( andsquare() are declared as follows: int square(int ny; double square(double x); the names of these functions, isquare and square, are pointers to those functions. We can assign them to pointer variables: fp = isquae; fptr= square: ‘The functions can now be accessed, i.e. called, by 0) and to f(a) <= g(a) for every input size n (n> no). Big-Omega Big-Omega, commonly written as Q, is an Asymptotic Notation for the best case, or a floor growth rate for a given function. It provides us with an asymptotic lower bound for the ‘growth rate of runtime of an algorithm. fn) is (g(a), if Hor some real constants ¢ (¢ > 0) and no (tg> 0), fin) is >= © g(n) for every = (n> ng) inputs Theta ‘Theta, commonly written as ©, is an Asymptotic Notation to denote the’ asymptotically tight bound on the growth rate of runtime of an algorithm. f(n) is @(@(n), if for some real constants cl, €2 and ng (el > 0, c2 > 0, np> 0), cl g(n) is < fin) is ng). + fla) is @(g(n)) implies f(n) is Ofg{a)) as well as f(a) is M(g{n)). Feel free to head over to ‘addtional resources for examples on this. Big-O is the primary notation use for general algorithm time complexity ‘G.8(c) Explain stack as Abstract data type (ADT) (2 Marks) ‘Ans. : Abstract data type (ADT) "The stack abstract data type is defined by the following structure and operations, A stack is structured, as described above, as an ordered collection of items where items are added to and removed from the end called the “top.” Stacks are ordered LIFO. Gen W Fundamentals of Data Structures (SPU) FDS-11 ‘The stack operations are given below. ‘Stack( creates @ new stack that is empty. It needs no parameters and returns an empty stack. pushitem) adds a new item to the top of the stack, It needs the item and returns nothing. popO removes the top item from the stack. It needs no parameters and ‘etums the item, The stack is modified. peek() returns the top item ‘rom the stack but does not remove it. It needs no parameters. The stack is not modified. isEmpty() tests to see whether the stack is ‘empty. It needs no parameters and retums a boolean value. size() retums the number of items on the stack. It needs no parameters and retums an integer. For example, ifs is a stack that has been created and starts out empty, then Table 1 shows the results of sequence of stack operations. Under stack contents, the top item is listed atthe far right. Chapter 9 : Searching and Sorting [Total Marks : 12] 3(¢) Explain the following terms ; (6 Marks) (Internal, (il) External (il) Sort stabitty. An (@ Internal Sorting : ‘An internal sorting process is any data sorting process that takes place entirely within the main memory of a computer. ‘This is possible whenever the data that has to be sorted is small enough to all be held in the main memory. For sorting larger datasets, it may be necessary to hold oniy a chunk of data in memory at a time, as it won't all fit. The rest ofthe data is mainly held on some larger, but slower medium (like a hard-disk). Any reading or writing of data to and from this slower media can slow the sorting process to considerable effect. Some common internal sorting algorithms are: 1. Bubble Sort 2. Insertion Sort 3. Quick Sort (External Sort: Extemal sorting i he sorting process that can handle massive amounts of data ata time. External sorting is requized when te data being sorted do not fit into the main memory of computing device (or the RAMand instead they must reside in the slower extemal memory (or the hard deve). External sorting typically uses ahybrid sort-menge strategy. In the Sorting phase, chunks of data small enough fo fit in main ‘memory ae read, sorted, and waiten out to «temporary file while inthe merge phase the sorted sub fies are combined {nto singe larger ile (ii) Sort Stability : When soning reconds in a table by a particular column or field, « stable sore will always retain the relative onder of records that have the same key, For example, in this table of Ceuntties an cies, «sable sort onthe second column, the cities, would keep the US Birmingham above the ‘UK Birmiagham. UK London US New York US Birmingham UK Birmingham Similars, suble soning, on jst the fst column would genenic "UK London” as the fist item and "US Birmingham’ a the lst item (since the order ofthe elements having the same first word ~ “UK” or “US” ~ would be maintained). arn Examine the documentation on any in-built sort routines supplied by a language, Indicate if an in-built routine is supplied If supplied, indicate whether or not the in-built routine is stable, aatey Write peeudo C code for insertion sort: Show all the passes to sort the values In ascending order using Insertion sort, values are : 5, 15,3,7,2. (6 Marke) Ane. : Pauedocode for Insertion Sort : Insertion Sort(A() 351872 ‘After Second Pass: 2357115 Hence, th outputs sorted. Chapter 10 : Linear Data Structures using Sequential Organization [Total 27) @.4(a) Explain linear data structure with sultable ‘example. (8 Marke) Ans. : Linear data structure Elements are arranged in a Linear fashion (one dimension). All one-one relation can be handled through Linear data structures, Lists, stacks and queues are examples of linear data structure. Representation of Linear data structures In an array 0” element ~ EDEL Fig1-Q4(a) WH Fundamentals of Data Structures (SPPI Representation of Linear data structures through Linked structure oF eomant dows [3—fS ES Sraaa of ho next element Top oe ES oS Ee Front 7 Fig2-Q-4) Gele) Wille a pseudo © algorithm for simple ‘tranepose of sparse matrix. What Is it time complexity ? ‘Ans. : Transpose of sparse “Transpose of a matrix is obtained by interchanging rows and columns. In another way, we can say that element in the i, j position gets pu in the ji postion. Transpose of the matrix B1 is obtained as B2 by inserting (th element of BI as (jth element inB2, (6 Marks) ‘The time complexity ofthe above program is O(n") .5(6) Explain row and column mejor storage representation of two dimensional array. (6 Marks) Ans. ‘There are two way of representing 2D array in memory: 1. Row Major: clements of array store in contiguous memory Tcations row by row. 2. Column Major: elements of array store in contiguous ‘memory locations column by column. @onnno FDS-12 S18 Suppose we have an aray| 6 4 7 932 ‘Row major Representation will be : 51,864,732 ‘Column major Representation willbe: $,69,1,43,8,7.2. 1 figure there is 3x3 array and memory location start from ‘200 and each element take 2 address. We can calculate element at ‘Array (3][1] for both row and column majoras follows: here m= m3 T = 3,je1, w=2, base address=200 Formula for row major Array (IG) = Base+w( nG-1)+6-1)) = 2004288-1)s(1-1)) = 212 Formula for column major Amy TOU] = Bases mG-1)+¢-1)) = 20028(1-143-1)) = 204 @.6{a) Explain sequential memory organization using ‘sultable data structure. (6 Marke) ‘Ans. : Sequential Memory Organization ‘In sequential organization the records are placed sequentially ‘onto the storage media i.e. occupy consecutive locations inthe case ‘of tape that means placing records adjacent to each other. Tn addition the physical sequence of records is ordered on some key called the primary Key. Sequential organization is also possible in the case of DASD such as a disk. Even though disk storage is really two dimensional (cylinder x surface) it may be ‘mapped down into one dimensional memory. If the disk has © cylinders and s surfaces one possibility will be to view disk ‘memory as in figure, Using notation tj to represent the jth tack of the ih surface, the sequence is t11, @1, G1...t81, 12, 22,-..ts2 ete. The sequential interpretation in figure is particularly efficient for batched update and retrieval as the tracks are to be accessed in, ‘order: all tracks on cylinder 1 followed by all tracks on cylinder 2 ‘etc, a5 a result of this the read/write heads are moved one cylinder ata time and this movement is necessitated only once for every § tracks. Its main advantages are: 1. Itiseasy to implement; 2. Tk provides fast access to the next record using lexicographic order. Its disadvantages: 1, Itis difficult to update - inserting a new record may require ‘moving a large proportion ofthe fle; 2, Random access is extremely slow. 66) Write an algorithm to add two sorted polynomial in a single variable . Analyze its ‘time complexity. (7 Marks) Ans. Algorithm to add two sorted polynomial in a single variable d(A(0.m-1), B(0.n01) 1) Create a sum array sum{] of size equal to maximum of ‘x! and’! 2) Copy Al] to sum 3) Travers array Band do following for every element BI) AN. i | Fundamentals of Data Structures (SPPU) FDS-13 sumfi] = sum] + BE) 4) Retum sum). ‘This algorithm explains the addition of two polynomials i single variable, Here, single array sum is used. Time complexity of the above algorithm and program is (O(men) where mand n are orders of two given polynomials. Chapter 11 : Linear Data Structures using Linked Organization [Total Marks : 26] 1. 7a) What Is generalized linked 7 Give graphical representation of the generalized list. (4 Marke) ‘Ans. : Generalized linked ‘A generalized linked list contains structures or elements with every one containing its own pointer. I's generalized ifthe list can hhave any deletions, insertions, and similar inserted effectively into it. Given :(126,455)).6) HEI ao Fa} HEY teenie rz mo e=neniene Fig. 1-Q.7() : Linked representation ofthe lists A, B and C 76) Compare between Single Link List and clreuter linked lst. (@ Marks) ‘Ans. :Comparison between Single and Circular Link List Single Link List ‘Gireular Link List [Last object points to] Last object points tothe first element NULL Ithes only next pointer to] Tt has FRONT and REAR pointers to| control the Link lst control the flow of data in the link ist [Used where dynamic|Used specifically where _ priority ‘memory allocation | Queues are to be implemented. required. @.7(c) Write pseudo code to delete a node from doubly linked list (DLL) (6 Marks) ‘Ans. : Delete a node from doubly linked list (DLL) @. 8(e) Compare array and link tet. ‘Ans. :Comparleon between Link List and Array Link List ‘Array It allocates memory | Generally, the memory dynamically as and when the | allocation is done statically that node is created. is before hand. Tt grows or shrinks as and | Its size remains fixed. ‘when required ‘Addition and deletion of | Addition and deletion of elements is very easy and | elements is not very easy and efficent. efficient. ‘Searching of the elements is | Searchin is very efficient. not very efficient. @.8(b) Write peeudo C code to insert a node at start ‘and end of singly inked list (SLL). (6 Marks) Ans. : Inserting a node at the stat of the Link List (@) Make a new node Gi) Point the ‘next’ of the new node to the ‘head’ of the linked list (Gi) Mark new node as ‘head’ ‘The code for the above steps is void front(int n) (8 Marke) Inserting at the end of linked list In this, we just add a new node atthe end of the existing list. So, the steps to add the end if a linked list is: Make anew node (Gi) Poin the lst node of the linked lst to the new node @o W Fundamentals of Data Structures (SPPU, FDS-14 Relational operators in C =| isequal to t= | isnot equal to <__| is ess than >| is greater than @.8(6) _ Give practical applications of linked let. “a ie ess han or ual (4 Marks) ‘Ane. Following ae he spptoations of Unk List >= _[[is greater than or equal to ‘A good example of an application where circulr linked list | Logleal Operators should be used is a timesharing problem solved by the Cas three logical operators: operating systemin a timesharing environment, the operating && logical AND I logical OR logical NOT system must maintain a list of present users and must alternately allow each user to use @ small slice of CPU time, fone user at a time. The operating system will pick a user, let hinvher use a small amount of CPU time and then move on to the next user, etc-For this application, there should be no [NULL pointers unless thee is absolutely no one requesting (CPU time. 2. Circular Link Lists (CLL) are also used in implementing, priority queves, 3. Circular lists are used in applications where the entire list is ‘accessed one-by-one in a loop. Example: Operating systems ‘may use it to switch between various running applications in ‘circular loop. 4, tis aso used by Operating system to share time for different users, generally uses Round-Robin time sharing mechanism. Multiplayer games uses circular lis to swap between players ina loop. Chapter 2: Operators and Expressions in ‘C’ [Total Marks -04] @.2{c) Explain various operators inc. (4 Marks) ‘Ans. : Arithmetic Operators: ‘C provide all the basic operators. Unary plus Addition =| Unary minus =| Subtraction 1. | Division % __| Moduio division (remainder) Relational Operators. ‘Two values can be compared with the help of a relational operator. An expression like x25; x45<: Containing relational operator is called a relations expression. ‘Value ofa relational expression is either one or zero. Value of relational expression is I, ifit evaluates to true. ‘Value of relational expression is 0, if it evaluates to false. More'than one condition can be combined with the help of logical operators. For example :x>5 && y<6; Kea 1(y<6) ‘Assignment Operator Result ofan expression can be stored in variable, with the help of assignment operator. aes (Sis assigned wo a); x= 345 {Sis assigned tox] X= x43 [Valueofxis increased by 3}; xX = x=1 [Value of xis decremented by 1] Shorthand aselgnment operators a= atl can be written as a4= 15 a atx can be writen as a4= x ae ax can be witen as a=; ae atx can be writen as a *=x a= alx can be wten asa /=x a = a%x can be writen as a = x Increment and Decrement Operators +++ is known as increment operator. ~ - is known as decrement operator. ‘The operator ++ adds 1 tothe operand while ~~ subtracts 1. ‘These operators can either precede or succeed the operand. “+4mis valid m+ is valid =-mis valid m-—is valid ‘+4m and mi+ give the same meaning when itis used as an independent statement. ++m and m+ behave differently when itis used in an assignment statement. Chapter 3 : Control Flow In ‘C’ [Total Marks - 06] Q.1(@) Write the difference between while and for loop In C language. (6 Marke) ‘Ans. : Do- while Statement ‘do-while loop is similar to while loop, except that the test condition is evaluated at the end of the loop and not at the ‘beginning. The general form of do-hileis given below : Arn W cundamentals of Data Stuctres (SPPU FDS-15 {for Statement for loop in C language ‘A while loop can be written more concisely using for loop. In for loop, the looping variable is automatically incremented. or decremented each time through the loop. The general form of for oop is given below : @.1(6) Explain call by value and call by reference with ‘suitable example, (6 Marks) ‘Ans. : Result of Passing Parameter by Value and by Reference Different methods for passing parameters to function °C’ allows passing of parameters : @ Byvalue Gil) By reference ‘When a parameter is passed by value, the calling program variable remains unaffected by whatever the function does to its local variables. When a parameter is passed by reference, the function can change the contents stored af the address. Example In the sample program given below: (1) There are two variations ofthe function increment, In the first ‘variation (incr! (), a parameter n is passed by value, whereas in the second variation (incr2 (), a parameter n is passed by reference, “Function inert () can not change the value of n dectared in the caling program. Function incr2 (is able to charge the value of n declared in the calling program. Output Chapter 6 : File Handling in [Total Marks - 04] Q.2(a) _Ditferentiate between Text file and Binary file, (4 Marks) ‘Ans. : Compare Text File and Binary File Text fle 1, Avtext file contains ASCIL value of text stored init. 2. A text file can be seen on monitor, it can be edited using any text editor. 43. tis easy to handle as contents are visible, 4. If text file is used as an input datafile, then there will be ‘additional overhead in converting integer numbers and floating point numbers to its equivalent intemal representation, ‘5. An integer or real numbers requires more storage area when stored in text format. ‘Binary file 1. A Binary file can be used for storing of text, graphics, image, sound data, 2 Integer or real number requires less storage area when stored in binary form. 3. fa binary file is used as an input datafile then there will not bbe any overhead in converting integer numbers and real ‘numbers to its equivalent internal representation. 4. Abbinary file is more compact and takes less storage area. ‘5. A binary file can not be created with the help of text editor ‘and hence itis difficult to handle, 6. Contents of binary file can not be seen directly on the monitor. Chapter 7 : Recursion [Total Marks - 04] @.2(b) What Is recursion ? Explain with example. (4 Marks) ‘Ans. : Recursion Recursion is « fundamental concept in mathematics. When a function is defined in terms of itself then itis called a recursive function. Consider the definition of factorial of a positive integer. 1 if o=0) Factorial (9) = * factorial (n—1), otherwise Function “factorial ( )" is defined in terms of itself for ‘n> 0. Value ofthe function at n = 0 is 1 and iti called the base Recursion terminates on reaching the base. W Fundamentals of D For example aoa (Teen Cee factorial ©) 1 Recursion expands when > O and it starts winding up on biting the base (n= 0). Chapter 8 : Introduction to Data Structures and Analysis of Algorithm [Total Marks - 12] Q.3(@) Define = (6 Marke) (1) Data and Data object (2) Data structure (@) Abstract Data Types Ans. (1) Data and Data object Data Data is a collection of numbers, alphabets and symbols ‘combined to represent information. A computer takes raw data as input and after processing of data it produces refined date as ‘output. We might say that computer science isthe stady of dat. ‘Atomic data are non-decomposible entity. For example, an integer value 523 or a character value ‘A’ cannot be further divided, If we further divide the value 523 in three digits ‘5 2° ‘and “3° then the meaning may be lost. ‘Composite data: It is a composition of several atomic data and hence it can be further divided into atomic data. Corto data ‘omic data Fig. 1-0.3¢0) For example, date of bith (say 15/3/1984) can be separated into three atomic values. First one gives the day of the month, second one gives the month and the last one isthe year. Data Object ‘Data object refers toa set of variables used ina program. I is place where the data values can be stored, retrieved and ‘manipulated Every data object is associated with datatype (type of value that can be stored) A complex object (structure type) can have a number of atsibutes. Data object can also be viewed as a runtime instance of adata structure. ‘Example : int x=0 ; xis the data object. 2) Data structure {A data structure is merely an instance of an ADT. An ADT or «structure is formally defined to be a triplet (D.F.A) where “D” «ads fora set of Domains, “F” denotes the set of operations and aon represents the axioms defining the functions in ‘example ofthe data structure “Natural Number (NATNO)". ‘Structure NATNO. Operations 1. ZERO()—> nano 2, ISZERO(aatno) —> boolean 3, SUCC{natno) -> natno 4, ADD(natno,natno) —> natno 5, EQUAL (natno, nano) > boolean. Axioms Forall x,y € natno let ISZERO(ZERO) is true ADDZERO,Y) is ¥ 8, EQUAL(x, ZERO), if ISZERO(x) then true else false D= { natno, boolean} F = (ZERO, ISZERO, SUC, ADD, EQUAL) A= {Line no 6 to 8 ofthe structure NATNO) (8) Abstract Data Types ‘The concept at abstraction is commonly found in computer science, A big program is never written as a monolithic piece of program, instead it is broken down in smaller modules (may be called a function or procedure ) and each module is developed independently. "When the program is hierarchical organized as shown in the Fig. 2-Q. 3(@, then the “main program” utilizes services of the fanctions appearing at level 1. Lovet Low Fig. 2-0. 3a) : Hierarchical organized program Similarly, functions writen at level 1 utilizes services of functions written at level 2. Main program uses the services atthe next level function without knowing their implementation detail. ‘Thus a level of abstraction is created. When an abstraction is created at any level, our concer is limited to “what it can do” and not “how its done”. Abstraction in case of data "Abstraction for primitive types (char, int, loa) is provided by the compiler. For example, we use integer type data and also, perform various operations on them without knowing them (1) representation @)_ how various operations are performed on them. Example int x, ¥,2 5 x=-13; Constant ~ 13 is converted to 2's complement and then stored {in x. Representation is handled by the compiler xay+z; Meaning of the operation ‘4 is defined by the compiler and implementation details remain hidden from the use. Implementation details (representation) and how various ‘operation are implemented remain hidden from the user. User is only concemed about, how to use these operations. W Fundamentals of Data Structures (SPPU FDS-17 Some of the most commonly used operations that can be performed on data structures are shown in Fig. 1-Q. 4(0). Objects such as lists, sets and graphs along with associated operations, canbe viewed as abstract datatype. Integer, char, real ae primitive datatypes and there are set of operations associated with them, Forte st ADT (Abstract datatype). ‘We might have operations like union, intersection, size and ‘complement. Once the data type set is defined (representation and associated functions) then the ADT set can be used in any ‘pplication program, ‘The Abstract Data Type “List” A list i a soquence of 0 or more elements of a given type (element type could be integer, flost et). Such a list is ofen represented as: 85 ene By 1n= Number of elements inthe list 44 =i" element of thelist ‘when m= 0, the ists empty having no element. ach element other than ay has a predecessor cach element, other than a, has a successor. In order to form an ADT from the mathematical notation ofa list, we must represent thelist and define a st of operations on objets of type List. Representation ofa List _Alistcan be represetedin'C’ wing a svete, B plmeece ‘Ais of maximum of 50 intege type elements ste actual number of elements in the List. ‘Asso repmenenative pereton o Lit Insert(L, XP): insert X at position Pin List L 2 tocweGct) Ts ton tee position of element X on List L 3. Retreve(L, P) : This function retums the element at position Pon list L 4, Delete(L, P): Delete the element at position P ofthe List L. 5. MAKENULL(L): Creates an empty List L 6. PrintList(L) : Print the elements of L in the order of ‘@.4(b)__ Differentiate between the following = (1) Primitive and Non-primitive data structures (2) Linear and Non-linear data structures (6 Marks) Ans. : 1. Primitive and Non-primitive data structures 1. Primitive : The integers, reals, logical data, character data, pointers and reference are primitive data structures. These data types are available in most programming languages as builtin type. Data objects ‘of primitive data types can be operated upon by ‘machine level instructions. 2 Nom-Primitive : These data structures are derived from primitive data structures. A set of homogeneous and heterogeneous data elements are stored together. Examples of Non-primitive data structures : Array, structure, union, linked. Fig. 1-Q. 4(b) : Data structure operations (2) Linear and Non-linear data structures: Linear Elements are arranged in a Linear fashion (one dimension). All one-one relation can be handled through Linear data structures. Lists, stacks and queues are examples of linear data structure. ‘Representation of Linear data structures in an aray aut ony ote (00 aman T oo [EE a Front Rear | | wos [op pepe = Representation of Linear data structures through Linked structure Auot loments tc Non-Linear All one-many, many-one or many-many relations are handled through non-linear data structures. Every data element can have a number of predecessors as well as successors. Tree graphs and tables are examples of non-linear data structures. raph @ © © Fig. 2-0. 4(b) : Non- Linear data structures W Fundamentals of Data Structures (SP root (@) Representation ofthe binary tree through linked structure (©) Representation of the binary tee through an array Fig. 1.0. 4(b) : Representation of tree of Fig. 2(8)-Q. 400) Chapter 9 : Searching and Sorting [Total Marks - 12] Q.3(b) Write algorithm to sort a lst of integers using bubble sort. Show output of each pass for the following list : 10, 5,4, 18, 17,1,2. (6 Marks) ‘Ans. : Bubble Sort Pseudo C Code for Bubble Sort ‘Bubble sort is one of the simplest and the most popular sorting method. ‘The basic idea behind bubble sort is as a bubble rises up in water, the smallest element goes tothe beginning, This method is ‘based on successive selecting. the smallest element through ‘exchange of adjacent element. 5 Rd _routot sequence, ence exchange LE caret queen neon ecarse 1 eaters ectungen eaten ee, Pint pan ofthe tient Let n be the number of elements in an array af }. The first pestageniertecnace aie: Nase aaron Caer is lene ee canoes Ths thal one now a3] compare ihe aan i Some te cna ta catego nas Sea on a{n — 3]. Comparison progresses backward and after the last Comparten of Al nd Af) ad posible thangs te smalls element will be placed at a{0). a cette ae pam cul bg compan i sy Su IN Ml tags a os see Soe stare on wb pce i a) er et spelen, Cotati fea ad eo at Cae cee anil te aye ale rosin $F Leet anus nesting 24D ceatewpere hemi 1 tart cane, . Lnfitperctomen nes ceme Seon Fist pass of the bubble sort with comparison in the forward ‘The second pass is an exact replica of the first pass except that this time, the pass ends with the comparison and possible exchange of a[n - 3} and ala ~ 2], After the end of second pass, the second largest element will be placed at afa -2}. Bubble sort requires a total of n~ 1 passes. fm ~ I elements are arranged (one element each pass) in ascending order form afl] to-a{n 1}, smallest element will finaly left at a[0). Loop for an arra nelements. Original array withn=6 5.96281 Fret pass = 1 Ino Up 6 2 U ¢ 2 26 I3 Topas = mo Rp etee congusine{ jas 2 gp 1 8 Parern rast omni pores creme 8 Fines ine congetenefino ai 6 8 8 8 Gen Fundamentals of Data Structures (SPPU) FDS-19 Soredamya]> 1 2 § 6 89 lustration of bubble sor. eC 5 4 10 17 1 2 1B) aterpaees 5 10 1 2 LAT 10) aterpucez 5 1 2 0 17 19) aterpases 12 [810 17 18) atorpases 2 6 10 7 18) atarpase 5 24 5 10 17 18) aterpans Further passes will have no effect and the data will remain as itis. ‘G.{@) _ Differentiate between the following (1) Internal sorting and External sorting (2) Linear and Binary searching (6 Marka) ‘Ans. : (1) Internal sorting and External sorting (@) Internal sorting Internal sorting takes place inthe main memory of the computer. Internal sorting can take advantage ofthe random acess nature ofthe main memory. Elements tobe sorted are stored in an integer array. These elements can be sored uring one of the ‘tious elgoritims discussed inthis chapter (b) © External sorting External sorting is caried on secondary storage, External sorting becomes a necessity ifthe number of elements o be sorted is too large oft in main memory. External sorting algortims should always tke into eocount that movement of data between secondary storage and main memory is best done by moving a block of contiguous elements. ‘Simple sorting algorithms like bubble sor, insertion sort take (4a?) time to sort.n elements. More complicated algorithms like ic sor, merge sort, heap sort take O(log n) time to sort n ements. Sorting algorithma like bubble sort, insertion sort, merge fon are sabe, Whereas quick sort and heap sor are unstable A Sorting algoritim is aid to be stable if after sorting, identical lements appear inte same sequence asin the original unsorted jis. (2) Linear and Binary searching ‘Binary search Linear search has time complexity O(a). such algorithms ae not suitable for searching when numberof elements is large. Binary search exhibits much better ming behaviour in case of large volume of data with ing complexity (og, ») ‘Number of comparisons for n = 2" (1 milion) Sequential search (in worst cae) = 2” comparisons. Binary search (in worst case) = log, 2””= 20 comparisons. Linear search (Gequential serch) may need 1. million comparisons for searching an element in an array baving 1 million elements. Binary serch wil require, jst 20 comparison forthe Same tsk. Binary search uses a mich beter method of searching. Binary search sepplicable only when the given ara is sorted. ‘This method makes «comparison between the “key” (clement toe searched) andthe middle element ofthe array. Since elements are sorted, comparisons may result in either match or comparison could be continued with citer let balf of elements or right half of the elements. . aon Left half of elements could be selected by simply making ject Right half of element could be selected by simply making iscel Process of selecting either the left half or the right half continues until the element is found or element isnot there. euch ominne Contr wearin Cantus sah mn Tenoaiste” rete ‘ores ‘sone iso leo [at nosten a! Chapter 10 : Linear Data Structures using nization [Total Marks: Explain simple and fast transpose of a sparse matrix with example. Also write fast tranepose function for sparse matrix. “(8 Marks) ‘Ans, :Transpose of a Sparee Matrix (Simple/siow) “Transpose of a matrix is obtained by interchanging rows and ‘columns, In another way, we can say that element in the i, j ‘Position gets put in the j,i position. “Transpose of the matix BI is obtained as B2 by inserting 9) element of BI as (,)" element in B2. @. 5(a) ete Fig. 1-0. 5(0) Algorithm for simple/slow transpose for @-= 1;i<=BI[O]2K 1+) t Bap(o) = BILL: BOGEN} = BILILO}: Bap] = BMI; ) B21] = BILOILNI: B2O}L1] = BILO}(O}; B2(0][2] = BI[OII; Elements of the matrix B2 are not in the required onder. Elements should be ordered on row and inside row, they should be ‘ordered on column. Thus the above method of finding transpose does not give the desired result. A modified algorithm for transpose (Produces an ordered lst). ‘Conversion of (jth element of BI to (ith element of B2 ‘must be done column wise W Fundamentals of Data Stuctres (SPF ‘An Algorithm without the above problem (Simple Transpose) Step 1 : Copy elements of column 0 from BI to B2 Fig.2-Q. (a): Blement (1, 0,5) is stored as (0, 1, 5) ‘Copy elements of column 1 from B1 to B2. Fig. 3-Q. 5(a) : Element (2, 1,1) is stored as (1,2, 1) Copy elements of column 2 from BI to B2. Fig. 4. 5(a): Element (0,2, 5)is stored as (2, 0, 5) Element (1, 2,3) is stored as (2, 1,3) Copy elements of column 3 from B1 to B2. Fig. 5-Q. 5(a) : Element (2, 3,2) is stored as (3, 2,2) ‘Algorithm works propery. Fast Transpose Fast Transpose of a Sparse Matrix Its another algorithm with much better timing behavior. Number of elements in each column of “B1[ J" is determined first. Ths gives numberof elements in each row of “B2[]". From the above information, the starting place ofeach row in “B2{ J" can be calculated exactly. | ‘Staring place Index row 0,4 row 1,3 row2,4 row 3,6 location 0 for staring m,n & t {row ,ooloums No. of Non = zero elements) 2 elements, row 0 1 element, row 1 1 element, row 2 2oloments, row 3 Fig. 6-Q. S(a): Showing starting place of each row in the transposed matrix “B2{ ” Example Ifnumber of elements in each column of BL > 2 1 Column number > 0 1 2.\, formatix BIE) 203 After transpose, numberof elements in each column of B1{] will become nuinber of elements in each row of B2. therefore, Number of elements in each row of B22. 1-1 2 row number 0123 eo | “undamentals of Data Structures (SPPU) FDS.21 ‘Row O starsat location 1 Peeudo-C Algorithm fo Fast Tran ‘Row 1 starts at 1+ cumulative sum of previous elements Fast transpose (A, BY! = 14283 row 2 stars at 1 + cumulative sum of previous elements aie (and index () are used ax (tn, ) = (A(O, 1), A, 2), A(0, 1),B(,2),BO,3)) = ‘Tow 3 starts at I + cumulative sum of previous elements = leRelenes op for counting of elements in each column of"B1{]” « bpeiet “indes() = indexGi— 4) + coal One, he tol numberof elem inex cola of "BIL" is calculated. Starting row index of each row in “B2{ J" can be calculated, int index MAX}; 4 {j= AGI) ‘i Blindex (j), 0), BlindexG), 1), Bede | Oo 2) index{O] = 1; /+ 08 row stats from location #/ (AG. 1,800), AG.2)5 for (i= tsi=0) yy om By Which is denoted by A. (8 jy. 8) ‘Elements of the linear list are atomic in nature. Elements of the linear list can be addressed by its index. ‘A= ()~An empty or null list. B = (a, b, c) ~ A list of three elements with B (1) = a, BQ)=band BG)=C. In a Generalized list, each element a, is either an atom or a list itself C=(@, 0, ), d)~ A list of three elements, First element ‘ai atomic. ‘Second element (b,¢) is ist ‘Third element ‘is atomic. Thus, a generalized list, A is finite sequence of n > = 0 clement a, 8... where each ais ether an atom ora list. Fundamentals of Data Structures (SPEL 1 is sad tobe the head of A. (tos) called the tall of A. Structure of node ‘When flag = 0, the node is data node ‘When flag = 1, the node is head node. o. (a,b, c(4,0,f),9,h) Fig. 1-0. 8(0) WY) ©.(498,0u)v) Fig.2-0.8(0) ‘@.8(6) Differentiate between sequential and tinked ‘organization. (4 Marks) ‘Ans.: Comparison between Array (Sequential) and Linked Lists ‘Array data structure is simple to use and itis supported by almost all programming languages. It is very simple to understand ‘and time to access any element from an aray is constant Advantages of sequential memory organization Simple to use Simple to define } Propetes of aay Constant acess time data severe Mapping by compiler ‘An array element can be accessed by afi, where ais the name of the array andi isthe index. : ‘Compiler maps afi] to its physical location’ in’ memory. ‘Address of afi i given by starting address of a + is size of array clement in bytes. This mapping is cartied out in constant time, irrespective of which element is accessed. Array data structure suffers from some severe limitations ‘Size of an array is defined at the time of programming. Insertion and deletion is time consuming. ‘Requires contiguous memory. First, the size of an array has to be defined when the program is being written and its space is calculated during compilation of ‘the program. This means that the programmer has to take a FDs.26 decision regarding the maximum sizeof data Ifthe actual amount of data stored is less than the maximum size, a good amount of ‘memory will be wasted and on the other hand a larger sample of data can not be handled. To avoid the linear cost of insertion and. deletion, we need to ensure that the list is not stored contiguously, since otherwise entire parts of list will need to be moved. Advantages of inked liste / linked memory 4) Linked lists an example of dynamic data structure. They can, ‘grow and shrink during execution of the program. i) Representation of linear data structure. (Inline data like polynomial, sack and queue can easily be represented using linked list. iii) Efficient memory utilization. Memory is not pre-allocated ike static data structure, Memory is allocated as per the need. ‘Memory is deallocated when it is no longer needed. Insertion and deletions are easier and efficient. Insertion and deletion of a given data can be carried out in constant time. Chapter 2 : Operators and Expressions in ‘C’ [Total Marks :03] .1(@) Explain working of diferent logical operators In with examples. (@ Maries) ‘Ans. : Logical operators in C Chas three logical operators ‘&& logical AND logical ORtlogical NOT More than one condition can be combined with the help of logical operators. Forexample: — x>5 ‘Some usetul conditions (© Coxpresion for 5 >x>2 x>2 && 55x (i) Cexpression for x les between aand b xoea && xed (ii) Cexpression for xis divisible by y xey =0 (Gv) expression for xis divisible by both y and'z xy == O&&X%2==0 (#) expression for xis divisible by y but not divisible by 2 xy = OREK%Z (i) Leas signiticant digit of «number xis 3 x% 10) ‘When a number 532i divided by 10, Quotient = 53. and remainder = (least significant digit) Chapter 3 : Control Flow In ‘C’ [Total Marks :03] @.1(b) Explain use of “break” and “Continue” keywords in C with suitable examples. (8 Marks) && y<6;x<25I1 19<6) ‘Ans. : Break Statement "The break statement allows you to “1 loop from any point ‘within its body, bypassing its normal ter nation expression. When the break statement is encountered Je a loop, the loop is ‘immediately terminated, and program cool resumes atthe next statement following the loop. The break statement can be used ‘with all three of Cs loops. You can have as many statements Po Teasy sotutions) | | | | | | ¥F Fundamentals of Data Sructures (SPPU) ‘within a loop as you desire. I is generally best to use the break for special purposes, not as your normal loop ext. break is also used in conjunction with functions and ease statements which will be covered in later sections. program showing break statement to end the loop. #inelude for(i=15i<=500;i++) { sum=sum +: iffsum>=30) breaks printf loop t print{('n Sum exceeds 30"); 3 Output Yooping looping Aooping Sum exceeds 30 Using the Continue Statement ‘The continue statement is somewhat the opposite of the break statzment. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of the loop. In while and do-whie loops, a continue statement will cause contol to go drety tothe test condition and then continue the looping process. Inthe case of the for loop, the increment part Of the loop continues. One good use of continue is to restart & statement sequence when an eroro2cur while(condition) { continue [| } Program showing use of continue, Program accepts input from the user and prints its reciprocal, ‘The process stops when ~ I is entered. The program skips printing of reciprocal if the number entered is 0. include void main() FDS-27 { float x: : while()) { ee -seanf("4el" Sex); if==-1) . if(e==0) continues printf("\nReciprocal of %f = %f",(1/x)); } + Output ‘htc number-I to terminata) 2 Reviprocal of 2.000000 = 0.500000, Enter a number(- to terminate) :0 Enter a number(- to terminate) Chapter 4: Arrays, Structure and Union [Total Marks :06] .2(b) What is the purpose of structure in C? Is it possible to define structure into the structure? Explain with suitable example, (6 Marks) Ans. : ‘Structures and its Purpose ‘We can create our own datatypes using structure. A structure type data can be composition of various other heterogeneous data types. Complex data types are represented using structures. Some of them are (linked tist () stack (©) queue (© polynomial © twee ‘Structure (@) Structure can be used for storing of heterogeneous data items. () Members ofa strctue are accessed using operator. (©) Complex data. types can declared as composition of heterogeneous data items and grouped together in 8 structure, ()_Steucure is basic building block for ADT. ©) Non-linear data structures like tee, graph etc. are handled using structure, Nested Structure Nesting of structures is allowed in ‘C’. Let us consider the following stractue defined to store information about a student. struct student ee { iat rllio; ‘struct { ‘char first_name(15]; ‘char middle_name (15); ‘har last_naine [15]; name: int marks: 1 Al components of a name are grouped together into a single substructure name. Variables declared in inner structure namely firstname, middle-name and lastname can be referred to as a WF Fundamentals of Data Structures (SPF Chapter 5 : Pointers [Total Marks : 17] @..2(e) What is output of following code: (2 Marks) Int array (] = (48, 67, 89}; Int* p= array; Print (*%d",*(P +4))5 @.5(a) Write address calculation for elements of one dimensional array. (2 Marks) ‘Ans. : Address Calculation in single (one) Dimension ‘Array: ‘Actual Ades ofthe 1% Momory space acquired edements ofthe By evar laments in ho aay Ishnow a8 "Array s called Base Address (8) wath ow) Here itis 1100 Here tis 4 bytes FDS. .5(¢) Write an algorithm to add two sorted Polynomial in a single variable, Analyze its time complexity. (7 Marks) Ans. : Lower LimiBoune of Subscrit 8) Fig. 1-510) ‘Array of an element of an array sty “A[ IJ” is calculated using the following formla: Address of A[1]=B+W*(1-LB) Where, B = Base address W. = Storage Size of one element stored inthe array Ga byte) = Subscript of element whose address is to be found LB = Lower limit / Lower Bound of, subscript if not specified assume 0 (2210) Example: Given the base address of an array B[1300....1900) as 1020 and size ofeach element is 2 bytes in the memory Find the address of B[1700). Soin. : ‘The given values are: B= J020, LB = 1300, W = Address of A [1] =B+W *(I-LB) 1020 + 2* (17001300) 1020 +2* 400 1020 + 800 1820 = 1700 Time Complexity : 0 (m+n) @.6(@) Explain the two dimensional arrays In detalle with column and row major Implementation and address calculation in both the case. (6 Marks) ‘Ans. : 2D row-major First, some notes on the nomenclature of this article. Computer memory will be represented as a linear aray with low addresses on the left and high addresses on the right. Also, wee going to use programmer notation for matrices: ows and columns Start with zero, atthe top-left comer of the matrix. Row indices go lover rows from top to bottom: column indices go over columns from left to right Go Fundamentals of Data Structures (SPPU) FDS-29 ‘As mentioned above, in row-major layout, the first row of the ‘matrix is placed in contiguous memory, then the second, and $0 on: 0.001102 oii i2 2.0121 [22 (eoTer ozo 120) Another way to describe row-major layout is that column indices change the fastest. This should be obvious by looking atthe linear layout atthe bottom of the diagram. If you read the element index pairs from left to right, youl notice thatthe column index. changes all the time, and the row index only changes once per row. For programmers, another important observation is that given ‘row index wir and a column index fey, the offset of the clement they denote in the linear representation is Of fset— ig, *NCOLS +i, Where NCOLS is the number of columns per row in the tmatrix, It's easy to see this equation fits the linear layout in the diagram shown above. 20 column-major Describing column-major 2D layout is just taking. the description of row-major and replacing every appearance of "row" by “column” and vice versa. The first column of the matrix is placed in contiguous memory, then the second, and soon 071 fo? rowcol [LOTTI 2 20121122 (eoTor ez oz 720) In colum-major layout, row indices change the fastest. The offset of an element in columi-major layout ean be found using this equation: Offset = gy * NROWS + gy Where NROWS is the number of rows per column in the matrix, Chapter 6 : File Handling in C [Total Marks :12] Explain the different modes of opening text and binary files in C using fopen( ) function, (6 Marks) a. 110) ‘Ans. : Files VO in ‘C* 5 Before a file can be used for reading or writing , it must be ‘opened. This is done by a call tothe fopen() function. The function fopen( requires two arguments (1). File name @) Option r,w, a, ete) Option indicates what we want to do withthe file (@) readit ©) wtiteto it (©) append toit (writing atthe end), For text file 1 open existing file for eating, Ww open (creat if necessary), discard pervious contents File ByteO Byle1 Byte? ByteS Byte4 Byles Byteé Byte7 Byte Byte9 Byte 10 open (creat if need be), do not discard previous contents, ‘write atthe end of the file. + open existing fle for reading and writing. It behaves like‘ ‘With the option of writing. ‘w+ create and open file fr reading and writing, discard previous contents. Itbehaves like “w" with the option of reading a+ open (create if need be) fle for reading and appending. It behaves lke ‘a’ withthe option for reading. For binary file 1 open an existing binary file for reading. wb. open (create if necessary) a binary fil, discard previous contents ab open (crete if ned be) a binary file, donot discard previous contents, wit at the end of the ile open an existing binary fle for reading and writing. It behaves like “" with the option of waiting. ‘wal create and open a binary file for reading and writing, discard previous contents. It behaves like “wb' withthe option of reading. 840 open (create if need be) binary fle for reading. and appeading. I behaves lke ‘ab’ with the option of reading. What is a file 2 A file can be treated as a steam of bytes. Size of a file is expressed in terms of numberof bytes in a fle. byte | byte 1 [ = [byten=2 [Bylo = Fig. 1-0.1(¢) A file of size n bytes A text file contains visible characters. We can see the contents of file on monitor o take its printout or et i using any ofthe text editors Examples of text fle A file containing & C-program A file containing a eter A file containing a text book A Text consist of. alphabets digits punctuation symbols spaces, tabs, end-of line, end-of file characters. ‘A characteris stored in afi by its ASCIL If we store a text A = B + C943 file will contain ‘Character [ASCH 41H Space 20H SDH 2H 2BH 43H 20H 39H 34H 33H >| beeraten ai | 20H] SDR | 20H | 42H | 2BH 43H | 20H | 39H | 34H [33H I A Space = Space B + Fig.2-Q.1(0): | I T T I Cc - 8 4 3 text file with text “A = B + C943" @onn “W Fundamentals of Data $ tuctures (SPPU meal ro Abinary file A byte consists of 8 bits. We in have total of 256 (2) combination of 8 bits. An ASCII is a7" bit code represented in 8 bits, ASCII has total of 128 2") codes out of them, fist 32 and the last code are control characters and they are not Visible. ‘Thus a byte may contain a value that may either not be a valid ASCII cade or it can not be displayed. Example of binary file (Q) Anexecutabe file (Le, prime. exe) (2) Anobject file (Le. prime. obj) ‘We can further understand the difference between i text file and a binary file knowing how the value of a variable can be stored in them, ‘Suppose x is short integer variable. It contains a number 125. (x= 125) Internally, x will contain the binary representation of 125 couiti01). ‘Storing x in a text file byteO ___ibyte_—_—byte2 [oa aaa ash \ ascilot ASCIr —ASCILor rn ‘ Fig. 3-0.1(0 : Storing 125 in text form (needs 3 bytes) Storing x in a binary file byw 0 Binary of 125 ‘Storing 125 in binary form (needs 1 byte) Fig. 4-0.1(6): Storing and integer value ina file G.2(@) What are different methods for passing parameters to function ? Write how array can be efficiently passed to a function with example, (6 Marks) Ans. : Different Methods of passing parameter are as below: ‘There are two ways by which we can pass the parameters to the functions: Call-by-value technique, the actual parameters in the method call are copied to the dummy’ parameters in the method definition. So, whatever changes are performed on the dummy parameters, they are not reflected on the actual parameters as the changes you ‘make are done to the copies and tothe originals. CCall-by-reference technique, reference (address) of the actual parameters are passed to the dummy parameters in the method definition. So, whatever changes are performed on the dummy parameters, they are reflected on the actual parameters t00 as both, references point to same memory locations containing the original values, ‘To make the concept more simple, let's consider the following code segment which demonstrates pass-by-value. This is ‘a program for exchanging values in two variables: ae € bey 3 ‘oid swapGint x inty) tie teenbs temp =x : x=n y= temp: y ) «lass SwapDemo { ‘publie stati void main(String] args) t Swapper obj = new Swapper(10, 20), ‘System cut.printin(“Before swapping value of “tobj.a-+” value of bis “-+obj.b}: swap(0bj.a,obj-b)s ‘System.out-peintin“ARier swapping value of ‘+tobj.a+” value of bis “+obj.b}s } 2 “The output of the above programming wil be: [Before swapping value of is 10 value afb is 20 ‘Alter swapping value of is 10 value of bis 20 Although values of x and y are interchanged, those changes are not reflected on a and b. Let's consider the following code segment which demonstrates pass-by-reference. This is program for exchanging values in two variables: ‘lass Swapper ane bey r | eee int temps temp = refs rela = ref; refb = temps ? & ‘lass SwapDemo « : | ae Swapper obj = new Swapper(10, 20); ‘System out:printin(“Bofore swapping value of ais MF objact” value ofb is “+0bjch); Geo un at 31 & Fundamentals of Data Structures (SPPU) FOS-31, abjaaplob Syatem.out printn(“After swapping value of a is “tobj.a+” value af bis “+obj.b); t £ ‘The output ofthe above programming will be: Before swapping valle of is 10 value of b is 20. ‘After swapping value of «is 20 value of bis 10 ‘The changes performed inside the methed swap are reflected fon aand bas we have passed the reference obj into ref thats very ‘much as using the same object within both brackets (from where it is called and to where its) which also points to the same memory Iocations as obj How array can be efficiently passed ‘to function with example C program to pass an array containing age of person to a function. This function should find average age and display the average age in main function, include float average(float age()); int main) 4 | loot avg, agef] = ( 23-4, 55, 22.6,3, 40.5, 18}, avg = average(age); /* Only name of array is passed as. ‘argument. */ ee print’ Average age=%6.2' avg): return 0; ‘loat average(float age[)) { int it. : a : ‘oat avg, sum = 0.0; : for(i = 051 <6; ++) { s ‘sum +5 ages } © eva = (oum/ 6); 5 Return avgy. } Chapter 8 : Introduction to Data Structures id Analysis of Algorithm [Total Marks :13 ] @.3(a) Explain the following terms (I) malioc() (ii) alloc (il) realloc{) (Iv) tree () (6 Marks) Ans 1) mau ‘The name malloc stands for "memory allocation” ‘The function malloc) reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form ‘Syntax of matloc() ‘pir = (Gast-aype¥) mallde(byte-size) Here, pris pointer of castiype. The mallot function returns 4 pointer to an area of memory with sie of byte size, Ii the space is insficient allocation fails and returns NULL pointer. Ar = (int*) malloo(100 * siscaftint)}p This statement will allocate ether 200 or 400 according to size of int 2 or 4 bytes respectively and the pointer points to the andres of ist byte of memory 1 catlocy) ‘The name calle stands for “contiguous allocation’. The only difference between malloc() and calloc() is that, malloc) allocates single block of memory whereas calloo) allocates multiple blocks of memory each of same size and sets all bytes o zero, ‘Syntax of calloc() ‘This statement will allocate contiguous space in an aray ofn clement, For example. : Bir = (oat*) calloo(25, sizeof(Most); ed This statement allocates contiguous space in memory for an array of 25 elemeats each of sizeof float ie, 4 bytes. i) free) Dynamically allocated memory created with either calloc) ot malloc() doesn't get feed on its own. You must explicitly use free()to release the space. ‘syntax of free() ‘This statement frees the space allocated in the memory pointed by ptr. Iv) realloc) If the previously allocated memory is insufficient or more than required, you can change the previously allocated memory size using reallocO. Syntax of reallocd) ir = realloeipi newaledi 4a) Explain the flowing terme () Big On notation (omega notation Gil) Theta Notation ae ‘Ans. : 1. Notation © ‘The function f(x) is ssid to be O(g(x) (pronounced as big ~ oh) if there exist two positive integerreal number constants C and such that £00) $ Cg) forall x2K Example iff Q)=2e 43041 then 3) $6x* forall x2 1 2x° +3: +1 = 068) as 9) SC. x’ for all x2 K where C= 6 and K = 1 ‘The notation O provides asymptotic upper bound for a given funetion. The purpose ofthe asymptotic growth rate notations and functions denoted by them is to facilitate the recognition of estental character of complexity function through some simpler function, Fundamentals of Data Structures (SPPU) ‘Notation ‘This provides asymptotic lower bound fora given function. A function f(x) is said to be & (x) (pronounced as big-omega) if ‘there exist two postive integerreal number constants C and K such that f(x) 2C (g(x) whenever x2 K Example ity) =28 43x04 then £0) 2C x forall x2 1,C=1 Dah + 3x41 268) 3. Notation © ‘This provides simultaneously both asymptotic upper bound and asymptotic lower bound for a given function. function fix) is said to be © (g(x) (pronounced big theta) if, there exist positive ‘constants C,, Cand K such that ats) $f(8) $C, e60 forall x2K. For any two fonctions f(x) and (9) £6) = 8 (g(8)) Hand only if fx) = O(g(s) and f(x) = 2 (9) @.a{b) What is_persistent and Ephemeral data structure ? (4 Marks) ‘Ans. : Persistent and Ephemeral Data Structure 'A dat structure is sud to be persistent if it can be accessed but ean not be modified. ‘Any operation on such data structure creates two versions of data structures. Previous version is saved and all changes are made in the new version. Thus an operation that changes the data wil create (Q)Acopy of old instanceof data structure with original vues. @)Acopy of new instance of data structure with updated values. Functional data structures are persistent. Tf we are able to create data cells and modify their contents, wwe can crete ephemeral data structures. These are data structures that change overtime, The mein advantage of such data structures is their ability to maintain state as shared resource among many routines. Another advantage in some case isthe ability to write code that is more time-effcient than purely functional code. ‘The disadvantage of ephemeral data structures are error and complexity. Our program can accidentally and irreversibly change the contents ofa data structure. Chapter 9 : Searching and Sorting [Total Marks :12] @.3(b) What is the importance of pivot elements in the quick sort method ? (2 Marks) ‘Ans. : Role of Pivot in Efficiency of Quick Sort ‘A choice of pivot, always influences the efficiency of quick sort algorithm. The popular choice of pivot as the first element is acceptable when input data is random. Ifthe input data isin either ascending or descending order, pivot will provide a poor partion Quick sort will require quadratic ime for sorting, (Quick sort will give its best behaviour when partition is found near center ofthe input data. In such a case, quick sort wll sort the data in (n logn) time. Median of the array is good choice for partition. Unfortunately, itis hard to calculate and would slow down quick sort.A good estimate can be obtained by picking three elements randomly and using the median of these thee as pivot AS an alternative, input data can be randomised and subsequently, frst clement can be taken as pivot FO: Q.3(c) Write pseudo C code for bubble sort ? Show Its working pass by reffrence for following data : 10, 4, 85, 21, 6. (4 Marks) ‘Ans. : UF program lor implenientstion of Bubble soit ‘include id swapQint "xp, int *yp) t — int temp = *xp; tp = yp; (bp temp: if (axe) > arnfj+ U0) swap(®arr{j], &arrfj+1))s fe Fanction 1 print an array ¥7 oid printAray(int arr}. int size) iste a = = Pfur (1051S Sieg ++) printed "ami; prin a) } {[PDaiver program to test above functions Sint main int ar{] = {64, 34, 25, 12, 22, 11, 90}; inn n= sizeof(arysizeoiarr{0); bubbleSor(arr,n)s printl’Sorted array: \n"); © paintAray(arr nls = rotwm 0; z ? ‘Working of given data pass b pass: ‘Given array with n = 6 is 10,04,55,21,06, First Pass = 1 1 455 21 6 410 55 216 f=2>4 10 21 85.6 aon 3 Fundamentals of Data Structures (SPPU FDS-33 10 2176" "58: 2 10 21 6 55 4 10 6 2 55 i=2 46 10 21 55 @.4(c) Write pseudo code for non-recursive binary search function and comment on its time complexity in best, average and worst cases. (6 Marks) ‘Ans. : Non-recursive binary search function #include #define MAX_LEN 10 /* Non-Recirsive function) void b_search_nonrecursive(int If}iat num,int ele) { int Hj fag = 05 =O; i= num; while < { j= +2; ii] == ele) ‘ { print((\nThe element Sis present at position Sd in Tistn'eles else ifQi] < ele) N=jth, lee ef ils } if( flag == 0) print{(\The element Sed is not present in the list\n",ele); + Time Complexity The numbers of comparisons for the recursive and non- recursive versions of Binary Search are the same, if comparison ‘counting is relaxed slightly For non-recursive Binary Search, count each pass through the while block as one comparison, Best case - 0 (1) comparisons In the best case, the item X-is the middle in the array A. A. ‘constant number of comparisons (actually just 1) are required. Worst case - 0 (log n) comparsions. In the worst case, the item X does not exist in the array A at all. Through each recursion or iteration of Binary Search, the size of the admissible range is halved. This halving can be done ceilinglog n ) times. Thus, ceiling(log n ) comparisons are required. Average case -O (log n) comparisons GOI Chapter 10 : Linear Data Structures using ‘Sequential Organization [Total Marks : 11] .5(b) Explain sequential memory organization with example. (4 Marks) An ‘Sequential Organization In sequential organization the records are placed sequentially ‘onto the storage media ie. occupy consecutive locations in the case ‘of tape that means placing records adjacent to each other. In addition the physical sequence of records is ordered on some key called the primary key. Sequential organization is also possible in the case of DASD such as a disk. Even though disk storage is really two dimensional (cylinder x surface) it may be mapped ‘down into one dimensional memory. Ifthe disk has c cylinders and ' surfaces one possibility willbe to view disk memory as in figure. Using notation tj to represent the jth track of the ith surface, the sequence is t11, Q1, 81... 12, 2,...ts2 ete. Fig. 1-Q.5(b) : Interpreting disk memory as sequential memory ‘The sequential interpretation in figure is particularly efficient for batched update and retrieval as the tracks are to be accessed in ‘order: all tracks on cylinder 1 followed by all tacks on cylinder 2 tc. asa result ofthis the read/write heads are moved one cylinder at & time and this movement is necessitated only once for every tracks. ‘Advantages are: Itis easy to implement; It provides fast access to the next ecord using lexicographic order. Disadvantages: It is difficult to update - inserting a new record may require ‘moving a large proportion ofthe fl Random access is extremely slow. ‘G6(b) What Ts sparse matrix 7 Explain how Wt Tepresented. Write C pseudo code for addition of two sparse matrices. What Is its time ‘complexity ? (7 Marks) Ans. : ‘Sparse Matrix as an Ordered List AA sparse matrix has many zero elements. For example, the following 4 x-4 matrix A isa sparse matrix, 090 0100 ete 8006 Fig. 1-0. 6(b): A sparse matrix Conventional method of representation of such a matrix is not space efficient. It will be prudent to store non-2ero elements only Ifthis is done, then the matrix may be thought of as an ordered list ‘of non-zero elements only. Information about non-zero elements have tree pars. Q) itsrow 2) itscolumn (3) its value 1 Fundamentals of Data Structures (SPP\ FDS-34 ‘Noo column vial mati Noten 2 No.of rom in ginal matic es ow Column Value Ne No. Fig. 2-Q. 6(b) : Sparse representation of matrix of Fig. 1-Q.6(6) ‘An efficient representation of a sparse: matix is an ordered list of 3-tuples of the form (ij, Va). When these tuples are stored in the lst, row numbers are increasing. For Any row number, column numbers are increasing. ‘Such a representation ofa sparse matrix of Fg. 1-Q.6() is shown inthe Fig. 2-Q60). Declaration of the matrix (Sparse matix stored as tples] int BEMAXI(3] 4 ‘maximum number of ows ‘The elements ‘B(O(0} - Contains numberof rows ‘BOI(1] ~Contains munber of columns B(0}(2] ~ Contains number of non-zero ters, ‘Addition of Two Sparse Matrices Chapter 11 : Linear Data Structures using Linked Organization [Total Marks : 13] Q.7(2) Explain concept of generalized linked list with, ‘example ? (4 Marks) BF eundamentals of Data Stuctures (SPPU) F0S-35 ‘Ans. : Representation of Generalized Lists ma} eed sete B=ialeede caceniene Fig. 1-Q. 7(a) : Linked representation ofthe lists A, B and C "Each node of a linked list can either be a head node ora data node (for atoms). ‘When flag = 0, the node is a data node. ‘When flag = 1, the node is a head node. ‘The field flag, identified whether the node isa data node or a head node. @.7(b) Write advantages of circular linked list over linear linked list. (2 Marks) ‘Ans. : Advantages of circular linked list 1) In circular link lst, the last node’s pointer is never NULL but pints back to the frst node. 2) In circular link list back traverse is possible but, which is not possible in linea linked list. 3) It concems the deletion operation. In Linear linked lst to delete desired node, itis necessary to give the address of first node ofthe list. 4) This necessity result from the fact that in order to delete desired node, the predecessor ofthis node has to be found. '5)__ The last node of linear linked list isnot used very effectively. Q.7(c) What is doubly linked list ? Write C code to delete a node from DLL at following position. (7 Marks) (tthe beginning (ii) Inthe middie (ii), Atthe end. Ans. : ‘A doubly linked lis sa linked data structure that consists of 4 set of sequentially linked records called nodes. Each node contains two fields, called links, that ae references tothe previous ‘and to the next node in the sequence of nodes. The beginning and. ending nodes’ previous and next links, respectively, point to some @omom ‘value ofthat node In a double linked ist, the deletion operation can be performed in thee ways as follows... (1) Atthe Beginning : (if) Delete in the middle: WF Fundamentals of Data Structures (SPPU) Question Papers 0.1 (@) Explain ony conrladionp srucurs inc (4 Marks) (0) What are advantages of using structure ? Ge 4 difference between union and structure. (4 Marks) (c) What is pointer variable ? Explain declaration, inaizaton and acossng pole variable wih an example. (4 Marks) OR Q.2 (a) Write pseudo C algorithm for reverse of string £ using pointers. (4 Marks) prin SUCCESSFULLY DELETED NODE FROM (b) Explain concept of arrays with suitable Seen) He POSTION tons (©) Balan cal by vate and cal by rtoence i tunetons wth Stabe exemple” (4 Mar) Q.3 (a) Define the following terms with example (ears) (i) Data object (li) Data structure (iti) Abstract data type. 1) We peeud Calgotns fo: (il) Delete the last node: (i) Linear search (9 Marks) ess (i) Binary search. (4 Marks) . on Q.4 (a) Explain Big-oh, omega and theta notation with example. (6 Marks) (©) Explain selection sort with given example by showing all passes. Also analyze time complexity. Number are: 17, 95, 24,13, 26, 14. . (7 Marks) @.5 (@) Write a pseudo C algorithm for addition of two = sparse matrices. Analyze its time complexity (6 Marks) (©) Explain the two-dimensional array in detail with column and row major repregentation and address calculation in both the cases. (6 Marks) oR 2.6 (a) Explain stack and write pseudo C algorithm for : PUSH and POP operations of stack. (6 Marks) x 2 (b) Explain polynomial representation of an array and ‘if dust != NULL) oe also wite data structure declaration with suitable Jast-> next = NULL; Remove link to of 2nd last example. (6 Marks) with lat node ©.7 (a) Explain concept of generalized linked list and = representation polynomial using GLL with given last = last->prev; // Move last pointer io 2nd last. one ee example :4e'+2x"+ Oxy +77" (6 Marks) Dele s © (&) Wite'C functon to inser @ node and delete rin SUCCESSFULLY DELETED NODE FRO © eden DL * nee & node and ace ® D $ “THE LIST.\n"); : OR (0.8 (6) Explain wth suitable example (6 Marks) () Circular tinked lst (i) Linked ist as an ADT. (b) Write a pseudo C algorithm to merge two sorted linked lists into the thir, (7 Marks) Fundamentals of Data Structures (SPPU) FOS-37 j May 2017 2.8 (a) Compare array and link ist (@ Marks) | (0) Write pseudo C code to insert a node at start and | .1 (@) Whatis the use of Void data ype? (2 Marks) end of singly linked list (SLL). (6 Marks) | (©) What is Macro ? Compare it with function (6) Give practical applications of linked list. | (4 Marks) (4 Marks) (©) Explain the use of pointer to array of structure with | suitable examph (2 Marks) eee | (©) Explain any four funetons used or le handing, | (a) we the aference between whe and for loop in | (4 Marks) language. ] neice (©) Explain call by value and cal by reference with 0.2 (a) Explain differant storage classes in ©. Yo example. (6 Marks) | (4 Mares) | © > (a) Ditferentate between Teft file and Binary fe. (©) What s pointer ? Explain pointer to function with (4 Marks) | suitable example. (6 Marks) ee ; a a (©) Differentiate between binary and text fie ©) What Ip recursion ? Expat ae | (4 Marks) | 2.3 (a) Explain -static and dynamic data structures with {©) | Explain vettous oporatora In. (4 Marke) | suitable examples. (@ Marke) | 0.3 (2) Define : (6 Marks) | (© What is space complexity of algorithm 7 Explain (1) Data and Data object Loreal a — (2) Data structure ° Aes mera: ne (@) Abstract Data Types (i) External (0) Write algorithm to sort a list of integers using bubble sort. Show output of each pass for the (i) Sort stabity. following ist: 10, 6,4, 18, 17, 1,2. (® Marks) oe Q.4 (a) Differentiate between the following: (6 Marks) ate ar ca snctre wi ae | ema eng end Bona og 1 (b) What are different asymptotic notation’? (3 Marks) (2) Linear and Binary searching (6) Wrte pseudo © code for insertion sort: Show all (0) Differentiate between the folowing : (6 Marks) 7 the passes fo sort the values in ascending order (1) Primitive and Non-primitive data structures Using insertion sort, values are: 5, 15, 3,7, 2. (2) Linear and Non-linear data structures (6 Marks) , 5 (a) Explain simple and fast transpose of a sparse Q.5 (a) Write @ pseudo C algorithm for simple transpose ‘matrix with example. Also write fast transpose ¢ j of sparse matrix. What sit time complexity ? function for sparse matrix. (8 Marks) ' (6 Maries) (&) Explain the concept of row major and column (©) Explain row and column major _ storage ‘major address calculation for mutidimensional representation of two dimensional array.(6 Marks) array using example. (6 Marks) (©) Explain stack as Abstract data type (ADT) | @.6 (a) Explain row and column major representation of a (2 Marks) matrix with example, (6 Marks) oR (©) Repreent the flowing promi sing eray () X84 10Ky* + 2x°V" + 18 2.6 (e) Explain sequential memory organization using ( suitable data structure. (6 Marks) (i) 9X + 2V'K + 8YX' + 17 (8 Marks) (0) Wite an algorithm to add two sorted polynomial in | °-7 (@) Witeshontnotes on: (o Morte) a single variable . Analyze its time complexity. Once incest 7a) |) tea‘ nono eee Sg ned He ©.7 (a) What is goneralized linked ? Give graphical Using three pointer. oY a Marks) representation of the generalizedist | (4 Marks) | q. g (a) What is generalized linked list 7 Represent the (©) Compare Linear ; mod circular linked it following ists (8 Marks) (3 Marks) (1) (@,b, ef, e, f), 9, h) (6) Write pseudo code to delete a node from doubly 2) @08,u).v) linked list (OLL) (6 Marks) | ©.8(b) Ditferentite between’ sequential and linked on organization (4 Marks) Gen Structures (SPPU) (ii) Theta Notation — (b) Whats persistent and Ephemeral data structure? Q.1 (a) Explain working of different logical operators in C (0) Write pseudo code for non-recursive binary with examples. (3 Marks) ‘search function and comment on its time (©) Explain use of oreek* and “Continue® keyword in complexity in best, average and worst cases. C with suitable examples. (8 Marks) (6 Marks) (c) Explain the diferent modes of opening text and | 2-5 (a) Write address calculation for elements of one binary files in C using fopent ) function. (6 Marks) ‘mensional array. (2 Marks) Q.2 (a) Whats output ot folowing code: (2 Marks) (©) -Eopleie serene! memory “orgénizaton wth example, (4 Merks) Int array )= (45, 67, 8}; : (6) Write an algorithm to add two sorted polynomial in Int* p =array; a single variable, Analyze its time complexity. Print ("eat (p +4) (7 Marks) Print (a, “pi oR b) What are diferent methods for padding | 2-6 (@) Explain the two dimensional arrays in details with Oat tnesen 20s how ee column and row major. implementation and SacntyT eesesul chat necsonTontTeamoe address calculation in both the case. (6 Marks) (6 Marks) (©) What is sparse matix ? Explain how it is Morar deeitaneer gt race aes represented. Write C pseudo code for addition of parameters to function ? Write how array ‘can be {wo sparse matrices. What i its time complexity ? efficiently passed to a function with example. (certo) (6 Marks) | 0.7 (a) Explain concept of generalized linked: lst with @.3 (a) Explain the following terme (i) mailoc() (i) colle example ? (4 Warns) (i) realioc{) (W) tree () (6 Marks) (6) Wrte advantages of circular linked list over linear (b) What is the importance of pivot elements in the eee (2 Marks) Quick sort method ? (@ Marks) (©) What is doubly linked list 2 Write C code to delete (©) Wrte pseudo © code for bubble sort 2 Show its a a mc working pass by pass for following data : 10, 4, (Maree) 55, 21,6. (4 Marks) ()Atthe beginning 2.4 (a) Explain the flowing terms : (8 Marks) (W) Inthe middle (Big Oh notation (i) Atthe ena, (i) Omega notation aaa Con ‘ { Fundamentals of Data Structures Statistical Anal Chapter No. | Dec. 2018 | May 2019 Chapter 1 06-Marks | 06 Marks Chapter 2 : : Chapters : : Chapter 4 : : Chapter 5 14 Marks | 12 Marks Chapter 6 04 Marks : Chapter 7 : 08 Marks Chapter 8 12.Marks | 09 Marks Chapter 9 12 Marks | 12 Marks Chapter 10 20 Marks | 26 Marks Chapter 11 82Marks | 21 Marks Repeated Questions | __- 27 Marks Chapter 1 : An Overview of C Language [Total Marks - 06] Q.4(c) List and explain the fundamental types in C. (2 Marks) Ans. Fundamental types In C (C-language has a varity of datatypes. User can select a type appropriate for a particular application. Most of the applications require ‘handling of integer numbers, real numbers and characters. C supports, following datatypes 1. Primary or Buin datatypes 2. User dened datatypes 3. Derived data types 4. Primary or builtin data types ~ These ae the fundamental datatypes supported by C-compiler."C” support thee basic datatypes 1. in integer 2. char, character 3. float, real numbers These datatypes too have variations in terms of size and representation. Structures (SPPU) Integer type ‘Signed type | Unsigned type (Only magnitude) int ‘Unsigned int short int ‘Unsigned short int long int ‘Unsigned short int Fig. 1-Q. 1(¢): Primary or basic data types in ‘C” = Size and range of basic data types Signed | Unsigned _ Char} Unsigned char ‘Floating point type et awaben: float | double | long double ‘Table 1-Q.1(¢): Size and range of data types on a 16-bit mic ee (bits) s (Char or signed char 8 [12810127 2's complement ASCIL ‘Unsigned char 8 | ow2s5 Binary ASCIL int or signed int 16 _| ~32,7681032,767 2°s complement Unsigned int 16 | 0165535 Binary ‘Short int or signed short int | 8 | ~ 12810127 2°s complement ‘Unsigned short int 8 _| or2ss Binary Long int or signed ongint | 32 _| 2,147,483, 648 to 2, 147, 483, 647 _| 2's complement ‘Unsigned long int 32 _ | 004,294, 967, 295 Binary Float 32 | 34B-38 034 +38 IEEE Double 64 | 1.78308 to 1.7E + 308 IEEE Long double 80 | 348-4932 10 1.1E +4932 TEE 2 Us r-defined type “type definition” allows user to define an identifier that wil represent an existing datatype. Forexample : [fyped — After above declaration, marks can be used for float. FDS2 — Here, marks are another name for float. Marks can be used to declare variables ofthe type flost. This approach, enhances readability of a program. Another user-defined datatype is enumerated data type. @One Fundamentals of Data Structures (SPPU) FDS. For example enum day (Mon, Tue, Wed, Thu Fri, Sat, Sun); enum day today ; — Variable today, which is declared of enum day type can be assigned a value from the set (Mon, Tue, Wed, Thu, Fr, Sat, Sun). Toda IF (today = ‘Today » Fri; A valid statement */ ‘Thu /* A valid statement +/ Mon) /* A valid statement +/ 3. Derived data types Array + A group of similar elements is stored in contiguous memory. Ex Int a6]; defining an array of size 6 gon | aft) | 9f2) | a(3) | af) | of5) int a[6} defines an integer aray of six elements, These elements are stored in contiguous memory locations. An element of the array is accessed as “afi]" where ais name ofthe array and ii index @.2{a) Explain memory allocation, declaration, access and initialization of structure variable with suitable exampl (4 Marks) = Memory allocation : Total memory allocated to a structure type variable is equal to sum total of memory required by its member field. = Initialization : When we declare a structure, memory can be allocated to initialized variable, Example: [Struct student {Char name(35}; int roling; ‘char addres(120}; lint gender; SIs [*Amit’, $5, “kothrad, Pane”, 1}; = Here, the structure is declared we have initialized the variable S1 Chapter 5 : Pointers [Total Marks - 14] Q.1(a) Explain dynamic memory allocation functions in C, (4 Marks) Ans.: Dynamic memory allocation functions in ~ Oneofthe most useflfeatures of Cis that itis posible to allocate memory to a program while itis executing. One doesnot ned declare in advance an aay to store the data. Quite often thesiae ofthe datas impossible to extimat beforehand ~The malloet) and catloo() fuetions of C are used to dynamically allocate memory. It retusa pointer to a block of n bytes of ‘memory allocated during runtime ifthe required memory eanot be allocated then it retums NULL. ~The pointer returned by caltoc( or malloc must be casted tothe appropriate pe Example for allocating énamic memory for storing 10 integer numbers using malloc); int °F; W_ Fundamentals of Data Structures (SPPU) FDS-4 P= (int *) malloc (100 * sizeoftint); TT ‘Address of block of memory is casted to address of integer. Number of bytes required for storing 100 integers. = On successful execution of the above statement, # memory space of the size 100 ¢ size of an integer in byte is reserved and the address ofthe first byte of the memory allocted is assigned tothe pointer P. — Example for allocating dynamic memory for storing 100 integer numbers using calloc). int *P; P= (int *)calloc(100, sizeoffint); ~The above statement allocates contiguous space for 100 blocks, each of size ‘sizeof{int). All bytes are initialized to zero and pointer 10 the first byte of allocated memory is assigned to pointer P. Q.4(b) Explain the following with example : (6 Marks) (1) Pointer to array (2) Pointer to pointer (8) Pointer to Array Ans. : 1. Pointers to array os 2 3 4 6 6 7 8 9 a [7 I I @ art a2 aed aed aS a6 ae? as0 8rd ¢—Addrone "8 “(aet)“(a42) “(as) “(er4) (an5) (ar6) (047) “as8) “(0r9) —Value P pet p2 AS ped prS pi pe? pv8 pa +— Address *p_ “D+t) (x2) “(o+3) “(p+4) “KO¥5) (p46) +7) (948) (D+) — Valve Fig. 1-Q. 1(b) : Address of array elements = Letus consider the case of an integer array : in a0}; = Amay occupies contiguous memory locaton. Its base address is given by &a{0] or simply 8. Base address of the array = &a [0] or a Address of the 0" element = base address or a ‘Address ofthe 1* clement =a + 1 Address ofthe element = a +i — fais the address ofthe i element in an array then value stored atthe address a + iis given by * (a+i). sere [el ser Semrert [ToT] aaa wenoy Fig. 2-0. 100) Ao Fundamentals of Data Structures (SPPU) FOSS In index notation, afi isthe value ofthe i* element of an array and &a[i] is its address. In pointer arithmetic, (a+ i) is the address of ‘the i element and * (a +i) is its value. ‘An array can also be accessed through user defined pointer. ive int *P, af10]; fis an integer pointer then P can be made to point to an array : PajorP=&al0}; [If contains the starting address ofan array then P + 1 P +2iis the address ofthe second element, the address of te first element, P+ iis the address ofthe i element. *P will give the value ofthe O* element. *(P +1) will give the value ofthe 1% element. *(P +i) will give the value ofthe i* element. ff Js an array then ais called a fixed pointer. We cannot assign a new value toa. Value of P can be changed. 2. Pointer to pointer = A pointer to pointer can store address of a pointer. It uses double indirection and can be used to store address ofa 2-D array. Example: intx,*P1, x Pts ax Pi P2=8P 1; Pal kK Fig. 3-0. 1(b) ‘Now, the contents ofthe variable x can be accessed through the pointer P2, which is given by **P2. Fundamentals of Data Structures (SPPU) FDS-6 Q.2(c) Explain the ways of parameter passing In C functions, (4 Marks) Ans.: Different methods for passing parameters to function = allows passing of parameters = © Byvalve ®)Byreference — When a parameter is passed by value, the calling program variable remains unaffected by whatever the function does to its local variables. When a parameter is passed by reference, the function can change the contents stored at the address. Example There ae two variations of te function increment nthe fit variation (incr! (),a parameter nis passed by valu, whereas in he second variation (incr 0), a parameter nis passed by reference — Function incr () cannot change the value of n declared in the calling program. = _ Function incr2 () is able to charge the value of n declared in the calling program. easy solutions]

You might also like