Regulation 2009 Ec 2202 Data Structures and Object Oriented

March 22, 2018 | Author: vdsrihari | Category: Class (Computer Programming), Control Flow, C++, Object (Computer Science), Array Data Type


Comments



Description

REGULATION 2009 EC 2202 DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING IN C++ 3 0 0 3 AIM To provide an in-depth knowledge in problem solvingtechniques and data structures. OBJECTIVES To learn the systematic way of solving problems To understand the different methods of organizing large amounts of data To learn to program in C++ To efficiently implement the different data structures To efficiently implement solutions for specific problems UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING 9 Introduction- Tokens-Expressions-contour Structures Functions in C++, classes and objects, constructors and destructors ,operators overloading and type conversions . UNIT II ADVANCED OBJECT ORIENTED PROGRAMMING 9 Inheritance, Extending classes, Pointers, Virtual functions and polymorphism, File Handling Templates ,Exception handling, Manipulating strings. UNIT III DATA STRUCTURES & ALGORITHMS 9 Algorithm, Analysis, Lists, Stacks and queues, Priority queues-Binary Heap-Application, Heaps hashinghash tables without linked lists UNIT IV NONLINEAR DATA STRUCTURES 9 Trees-Binary trees, search tree ADT, AVL trees, Graph Algorithms-Topological sort, shortest path algorithm network flow problems-minimum spanning tree - Introduction to NP - completeness. UNIT V SORTING AND SEARCHING 9 Sorting Insertion sort, Shell sort, Heap sort, Merge sort, Quick sort, Indirect sorting, Bucket sort, Introduction to Algorithm Design Techniques Greedy algorithm (Minimum Spanning Tree), Divide and Conquer (Merge Sort), Dynamic Programming (All pairs Shortest Path Problem). Total hours = 45 TEXT BOOKS: 1. Mark Allen Weiss, Data Structures and Algorithm Analysis in C , 3rd ed, Pearson Education Asia, 2007. 2. E. Balagurusamy, Object Oriented Programming with C++ , McGraw Hill Company Ltd., 2007. REFERENCES: 1. Michael T. Goodrich, Data Structures and Algorithm Analysis in C++ , Wiley student edition, 2007. 2. Sahni, Data Structures Using C++ , The McGraw-Hill, 2006. 3. Seymour, Data Structures , The McGraw-Hill, 2007. 4. Jean Paul Tremblay & Paul G.Sorenson, An Introduction to data structures with applications, Tata McGraw Hill edition, II Edition, 2002. 5. John R.Hubbard, Schaum s outline of theory and problem of data structure with C++, McGraw-Hill, New Delhi, 2000. 6. Bjarne Stroustrup, The C++ Programming Language, Addison Wesley, 2000 7. Robert Lafore, Object oriented programming in C++, Galgotia Publication UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING Introduction- Tokens-Expressions-contour Structures Functions in C++, classes and objects, constructors and destructors ,operators overloading and type conversions . PART A 1. What is an identifier? Identifiers are names for various programming elements in c++ program. such as variables, arrays, function, structures, union, labels ect., An identifier can be Composed only of uppercase, lower case letter, underscore and digits, but should start only with an alphabet or an underscore. 2. What is a keyword? Keywords are word whose meanings have been already defined in the c compiler. They are also called as reserved words. (ex) main(), if, else, else, if, scanf, printf, switch, for, goto, while ect., 3. Define constant in c++. Constants in c++ refers to fixed values that do not change during execution of a program. 4. Define a variable. A quantity ,Which may vary during execution of a program is called as a variable. 5. What are unary operators? The operators that act upon a single operand are called as unary operators. The unary operators used in c++ are - , ++, -- and sizeof operators. 6. What are binary operators? The operators that act upon two operands are called binary operators. The binary operators used in c++ are +, -, *, / , %, =. etc., 7. What are ternary operators? The operators that act upon three operands are called as ternary operators. The ternary operator available in c++ is (?:).This operator is also referred as conditional operator. 8. What is meant by an expression? An expression is a combination of constant, variable, operators and function calls written in any form as per the syntax of the c++ language. 9. State the difference between c and c++. C C++ (i). Procedural programming language Object-oriented programming anguage (ii) Global variable can be declared It is an error to declare a variable as global (iii) Function prototypes are optional All functions must be prototyped. (iv) Local variables can be declared only Local variables can be declared any where the start of a c program in a c++ program. (v) We can call a main() function, within This is not allowed a program. 10. List the various oops concepts Four main OOP concepts Abstraction creation of well-defined interface for an object, separate from its implementation e.g., key functionalities (init, add, delete, count, print) which can be called independently of knowing how an object is implemented Encapsulation keeping implementation details private i.e., inside the implementation hierarchy an object is defined in terms of other objects Composition => larger objects out of smaller ones Inheritance => properties of smaller objects are inherited by larger objects Polymorphism use code transparently for all types of same class of object i.e., morph one object into another object within same hierarchy 11. Define class and object Class: It is defined as blueprint or it is a collection of objects Define encapsulation Encapsulation is one of thr most important features of a class. Define inheritance Inheritance Objects are often defined in terms of hierarchical classes with a base class and one or more levels of classes that inherit from the classes that are above it in the hierarchy. 12. Creation of well-defined interface for an object. the default privacy specification is public Example: class point { double x. }. public: // Declarations of additional members..Objects: is an instance of a class Almost like struct. protected: // Declarations of additional members. Define abstraction. print) which can be called independently of knowing how an object is implemented 15. } 13. separate from its implementation e. if needed.g. double v ). if needed.It is the process os combining member functions and the data it manipulates by logically binding the data ane keeping them safe from outside interference. Define polymorphism Polymorphism means having many forms . delete. add. It allows different objects to respond to the same message . the default privacy specification is private whereas with struct. graphics objects might be defined as follows: Syntax for Inheritance class derivedClass : public baseClass { private : // Declarations of additional members. For instance. key functionalities (init. void set( double u. y. 14. if needed. // implicitly private public: void print(). count. 21. E. 16. The purpose of the exception handling mechanism is to provide a means to detect and report an exceptional circumstance so that appropriate action can be taken. the enrolment number). we can make that function an inline function and we can mainly go for inline function to eliminate the cost of calls to small functions.g. List out the application of oops.g. Client server computing Simulation such as flight simulations. When will you make a function inline? When the function definition is small. Syntax: :: variable name 22. such as process control. Object-oriented database applications. the response specific to the type of the object. 22. as it uses a stricter syntax and type checking. `Data hiding'. It is used to uncover a hidden variable. There are 2 types of overloading: . List out the benefits of oops. the global version of the variable cannot be accessed from within the inner block. the usage of data by one program part while other program parts cannot access the data Will whiten your teeth 19. 20. Real time systems.in different ways. What is overloading? Overloading refers to the use of the same thing for different purposes. Define data hiding. the message displayDetails() of the Person class should give different results when send to a Student object (e. Can create new programs faster because we can reuse code Easier to create new data types Easier memory management Programs should be less bug-prone. Artificial intelligence and expert system Computer aided design and manufacturing systems. temperature control. What is the use of scope resolution operator? In C. C++ resolves this problem by introducing a new operator :: called the scope resolution operator. . They should be declared in the public section. Define modular programming. What are objects? How are they created? Objects are basic run-time entities in an object-oriented programming system. . 25. Constructors cannot be virtual.objn.Function overloading Operator overloading 23. Describe the importance of destructor. It is a member function whose name is the same as the class name but is preceded by a tilde. Objects are created by using the syntax: classname obj1. They do not have return types. Recursive function can t be directly invoked by main function 24. (or) during definition of the class: class classname { ------------}obj1.objn. Syntax: ~classname(){ } 27. . A destructor destroys the objects that have been created by a constructor upon exit from the program or block to release memory space for future use. they can have default arguments 26. They are invoked automatically when the objects are created. The class variables are known as objects. List some of the special properties of constructor function.obj2. Like other C++ functions.obj2. What is the difference between normal function and a recursive function? A recursive function is a function. not even void and cannot return values. which call it whereas a normal function does not. Modules should be designed. What do you mean by friend functions? C++ allows some common functions to be made friendly with any number of classes. 32. What is the use of new operator? The new operator is used to allocate contiguous unnamed memory during execution time ane returns a pointer to the start of it. Mention the types of polymorphism. 31. Define dynamic binding. Constructor Destructor A constructor is used to initialize the object A destructor is used for releasing dynamically allocated memory No symbol precedes the class name A tilde symbol precedes the class name Constructors can be overloaded Destructors cannot be overloaded 33. 34. State the difference between a constructor and destructor. which helps in easy error checking. What is the use of static data member? The static data member informs the compiler that only one copy of the data member exit and all objects . thereby allowing the function to have access to the private data of thse classes. 29.It is a process of splitting a large program in to smaller modules to perform the operations fast and. What are member functions? Functions that are declared within the class definition are referred as member function. The types of polymorphism are ? compile time polymorphism ? runtime polymorphism 30. implemented and documented with regard to their possible future use in other projects. Such common functions are called friend functions. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time. Such a function need not be a member of any of these classes. 28. as it uses a stricter syntax and type checking. the usage of data by one program part while other program parts cannot access the data Will whiten your teeth Demerits: disadvantages of C++ over Java: Java protects you from making mistakes that C/C++ don t. increments the value of a by 1. Start of loop b) The break statement when executed The continue statement when causes Immediate termination of loop executed caused immediate containing it. While loop do-while loop a) The while loop tests the condition The do-while loop tests the condition before each iteration after the first iteration b) If the condition fails initially the loop Even if the condition fails initially Is skipped entirely even in the first the loop is executed once Iteration. State the merits and demerits of object oriented methodology. `Data hiding'. Break continue a) Used to terminate the loops or to Used to transfer the control to the Exit loop from a switch. termination of the current iteration of the loop. 36.of the class should share that variable without duplicating it for each instance of the class. function overloading and virtual functions can very quickly make C++ programs very complicated . Distinguish between break and continue statement.before a is used for computation. PART B (16 MARK) 1. 37. Distinguish between while and do-while loop. while a post-increment operation such as a++. 35. A pre-increment operation such as ++a. uses the current value or present value of a in the calculation and then increments the value of a by 1. What is the different between a pre-increment and post-increment operator. Merits: Can create new programs faster because we can reuse code Easier to create new data types Easier memory management Programs should be less bug-prone. as you ve C++ has many concepts and possibilities so it has a steep learning curve extensive use of operator overloading. For example. Abstraction represents the act of representing the essential features without including the background details or explanations. Objects can interact without having to know the details of each others data or code. a bank account or any item that the program has to handle. Explain the basic concepts of object oriented programming in detail with example. In short. time and lists. the bird robin is a part of the class flying bird which is again a part of the class bird . a class serves as a blueprint or a plan or a template.shortcuts offered in C++ can often make it completely unreadable. They may represent userdefined data such as vectors. When a program is executed. Each object contains data and code to manipulate the data. Data Abstraction and Encapsulation: The wrapping up of data and functions into a single unit is known as encapsulation. Once class has been defined we can create any number of objects belonging to that class. These functions provide interface b/n the object s data and the program. Since the classes use the concept of data abstraction. Inheritance: It is the process by which objects of one class acquire the properties of objects of another class. just like in C 2. Defining the class doesn t create any objects. the objects interact by sending messages to another. It supports the concept of hierarchical classification. The data is not accessible to the outside world and only those functions which are wrapped in the class can access it. and the type of message accepted and the type of response returned by the objects. just as the mere existence of a type int doesn t create any variables. . They may represent a person. It is sufficient to know the type of message accepted. Programming problem is analyzed in terms of objects and the nature of communication b/n them. It specifies what data and what functions will be included in objects of that class. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size. In fact the objects are variable of the type class. BASIC CONCEPTS OF OBJECT ORIENTED PROGRAMMING These include: ? Objects ? Classes ? Data abstraction and encapsulation ? Inheritance ? Polymorphism ? Dynamic binding ? Message passing Objects: Objects are the basic run-time entities in an object oriented programming. It is the most striking feature of the class. weight and cost and functions to operate on these attributes. The attributes are called data members and functions are called member functions or methods. they are known as Abstract Data Types (ADT). a place. This insulation of the data from direct access by the program is called data hiding or information hiding. Classes: The entire set of data and code of an object can made a user defined data type with the help of a class. Object: employee Message: salary Information: name 3. State the rules to be followed while overloading an operator. It allows objects to have different internal structures to share the same external interface. The behavior depends upon the types of data used in the operation.This concept provides the idea of reusability. Message passing involves specifying the name of the object. The new class will have the combined features of both the classes. . the name of the function (message) and the information to be sent.salary(name). It is associated with the polymorphism and inheritance. A single function name can be used to handle different types of tasks based on the number and types of arguments.g. This means that we can add additional features to an existing class without modifying it. This is possible by a deriving a new class from an existing one. E. For example the operation addition will generate sum if the operands are numbers whereas if the operands are strings then the operation would produce a third string by concatenation.write a program to illustrate overloading. Message Passing: The process of programming in OOP involves the following basic steps: ? Creating classes that define objects and their behavior ? Creating objects from class definitions ? Establishing communication among objects A message for an object is request for execution of a procedure and therefore will invoke a function (procedure) in the receiving object that generates the desired result. Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in response to the call. This is known as function overloading.: employee. OPERATOR OVERLOADING: Operator overloading means giving additional meaning to existing operators By operator overloading an existing operator can be made to perform different operations than the stipulated one. An operation may exhibit different behavior in different instances. Polymorphism: It means the ability to take more than one form. The process of making an operator to exhibit different behaviors in different instances is known as operator overloading. Dynamic Binding (late binding) means the code associated with the given procedure call is not known until the time of the call at run-time. . OVERLOADING UNARY OPERATOR: Unary operators like unary + . can be overloaded as follows EXAMPLE: #include #include class unary { int a. } Generally there are three general classifications of operator namely Operator Unary binary ternary Among the above unary and binary operators can be overloaded and ternary operator cannot be overloaded. public: void get() { a=10.*) SYNTAX: Return-type operator op-symbol(argument list) { body of the function. Almost all the operators in c++ can be overloaded except the following o Sizeof () o Conditional operator (?:) o Scope resolution operator (::) o Class member access operator (..It doesn t change the meaning and precedence of the original operator. Unary .. .. get(). In this an object u is created and given the value 10 When the unary operator is called the operator function is invoked and the value of the member data of the object u is negated.show(). //unary operator . } void operator . . The negated value is then displayed. u. -u. } }.} void show() { cout <<"\n The value of the object is\n"<<a. void main() { clrscr(). getch(). the unary operator minus is overloaded. } O/P: The value of the object is 10 The value of the object is -10 In the above program.called u.() { a=-a. unary u. u.show(). cout<< mul(a.32. (i)Describe the application of oop technology Applications of OOP: ? Real time systems ? Simulation and modeling ? AI and expert systems ? Neural networks and parallel programming.b). Decision support and office automation systems (ii)What is an inline function? INLINE FUNCTIONS : An inline function is a function that is expanded in line when it is invoked. the complier replaces the function call with the corresponding function code. float y) { return (x*y). double q) { return( p / q ) } int main() { float a=12.The inline function are defined as follows: inline function header { function body } Example : inline int cube(int a) { return (a*a*a). That is . float b=9.35.4. } inline float div(double p. } Program : #include inline float mul(float x. cout<<div(a. return 0. .b). It is special because its name is the same as the class name. Constructor: A constructor is a special member function whose task is to initialize the objects of its class. // object is created // some code } During the object creation. A constructor is declared and defined as follows: class sample { int m.Explain copy constructor with suitable c++ coding. public: sample() { m = n = 0. it also initializes the data member s m and n to 0. void main() { sample s.} 5. Characteristics of a constructor: ? They should be declared in the public section ? They are invoked automatically when the objects are created ? They do not have return types ? They cannot be inherited ? They can have default arguments ? It cannot be virtual ? We cannot refer to their addresses ? An object with a constructor or destructor can not be used as a member of a union ? They make implicit calls to the operators new and delete when memory allocation is required Copy constructor: A copy constructor takes a reference to an object of the same class as itself as an argument. Example: . (i). The constructor is invoked whenever an object of its associated class it s created.n. Default Constructor: A constructor that accepts no parameters is called the default constructor. } // some code }. assigns 25 to x and 35 to y (ii). int b = 10) Inside the main(): sample s2(20). } Generally there are three general classifications of operator namely Operator Unary binary ternary Among the above unary and binary operators can be overloaded and ternary operator cannot be . assigns 20 to x and 10 to y.List out the rules for overloading operator. Almost all the operators in c++ can be overloaded except the following o Sizeof () o Conditional operator (?:) o Scope resolution operator (::) o Class member access operator (. where as sample s5(25. Example: Inside the class definition: sample(int a.It sets the value of every data element of s3 to the value of the corresponding data element of s2 Constructors with default arguments: It is possible to define constructors with default arguments.35) .*) SYNTAX: Return-type operator op-symbol(argument list) { body of the function. It doesn t change the meaning and precedence of the original operator.. OPERATOR OVERLOADING: Operator overloading means giving additional meaning to existing operators By operator overloading an existing operator can be made to perform different operations than the stipulated one.. Do while and the while statement. While loop do-while loop c) The while loop tests the condition The do-while loop tests the condition before each iteration after the first iteration d) If the condition fails initially the loop Even if the condition fails initially Is skipped entirely even in the first the loop is executed once Iteration. File Handling Templates. Manipulating strings. Compare and contrast the following control structure with example: (i). Break continue a) Used to terminate the loops or to Used to transfer the control to the Exit loop from a switch. . Virtual functions and polymorphism.overloaded. Pointers. (ii). Exception handling. Start of loop b) The break statement when executed The continue statement when causes Immediate termination of loop executed caused immediate containing it. Extending classes. break statement & continue statement. 6. termination of the current iteration of the loop. UNIT II ADVANCED OBJECT ORIENTED PROGRAMMING Inheritance. . 6. Multiple inheritance. Mention the types of inheritance. Hierarchical inheritance. If several inheritance paths are employed for a single derived class the base class must be appropriately declared 5. 4. Multilevel inheritance.*) ? Conditional operator (?:) 2. 7. Visibility modes must be taken care of. 3. 5. regardless of how many inheritance paths exist between the virtual base class and a derived class. 2. What are the rules governing the declaration of a class of multiple inheritance? More than one class name should be specified after the : symbol.PART A 1. What is the difference between base class and derived class? The biggest difference between the base class and the derived class is that the derived class contains the data members of both the base and its own data members. Hybrid inheritance. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time. . What is a virtual base class? When a class is declared as virtual c++ takes care to see that only copy of that class is inherited. Define dynamic binding. 4. 3. What do u mean by pure virtual functions? A pure virtual function is a function declared in a base class that has no definition relative to the base . Single inheritance. The other difference is based on the visibility modes of the data members. What are the c++ operators that cannot be overloaded? ? Size operator (sizeof) ? Scope resolution operator (::) ? Class member access operators(. Give the general format of class template. the overloading resolution is accomplished as follows: 1) Call an ordinary function that has an exact match. the templates are sometimes called parameterized classes or functions 9. What are templates? Templates enable us to define generic classes. 8. The general format of a class template is: template class classname { // //class member specification //with anonymous type T //wherever appropriate // }. 2) Call a template function that could be created with an exact match. in such cases. 11. a template function can be overloaded either by template functions or ordinary functions of its name.class. 3) Try normal overloading resolution to ordinary functions and call the one that matches. Since a template is defined with a parameter that would be replaced by the specific data type at the time of actual use of the class or function. In such cases. A template can be considered as a kind of macro. 12. When an object of a specific type is defined for actual use. Yes. List the kinds of exception. What is exception handling? The purpose of the exception handling mechanism is to provide a means to detect and report an exceptional circumstance so that appropriate action can be taken. A class containing pure virtual functions cannot be used to declare any objects of its own. Can we overlaod template function if so explain how. the template definition for that class is substituted with the required data type. the compiler requires each derived class to either define the function or redeclare it as a pure virtual function. 10. Exceptions are of two kinds namely Synchronous exceptions . What are the errors in synchronous type exceptions? Errors such as out-of-range index and over-flow belong to the synchronous type exceptions. Mention the key words used in exception handling.Asynchronous exceptions 13. The syntax of exception handling mechanism is as follows: try { --------------------throw exception --------------------} catch(type arguments) { ----------------------------------------} ---------------------- . The keywords used in exception handling are throw try catch 17. 3) Receive the error information (Catch the exception). 4) Take corrective actions (Handle the exception). What are the errors in asynchronous type exceptions? The errors that ware caused by errors beyond the control of the program (such as keyboard interrupts) are called asynchronous exceptions. 2) Inform that an error has occurred (Throw the exception). Give the syntax of exception handling mechanism. 16. What are the tasks that are performed by the error handling mechanism? The mechanism suggests a separate error handling code that performs the following tasks: 1) Find the problem (Hit the exception). 14. 15. fill( * ). The ios format functions are as follows: width() precision() fill() setf() unsetf() 19. List the manipulators. List the ios format function. Manipulator Equivalent ios function setw(int w) width() setprecision(int d) precision() setfill(int c) fill() setiosflags(long f) setf() resetiosflags(long f) unsetf() endl \n 21. For example. where ch represents the character which is used for filling the unused positions.fill(ch). the statements cout. cout<<5250<< \n . It is used in the following form: cout. Define fill functions. will produce the following output: PART B .width(10). Mention the equicalent ios function for manipulators. The manipulators are: setw() setprecision() setfill() setiosflags() resetiosflags() 20. cout.---------------------18. The fill( ) function can be used to fill the unused positions of the field by any desired character rather than by white spaces (by default). cin >>a. Multiple inheritance: It is a type of inheritance in which a class can inherit properties from more than one class. Explain hybrid inheritance with suitable C++ coding. class bc2 . 2. INHERITANCE: Inheritance is a mechanism of deriving a new class from a old class.visibilitmode baseclass2 { body of the derived class.1. } }. The class which provides the properties is called as base class and the class which derives the properties is called as derived class. Syntax: Class derivedclass name : visibility mode baseclass1. public : void get() { cout << \n enter the value for a\n . visibility mode can be either private or public. }. Explain multiple inheritances with suitable c++ coding. Example : #include #include class bc1 { protected: int a. It provides the concept of reusability By inheritance some or all the properties of a class can be derived in to another class. cout <<a<< \n <<b. void main() { clrscr(). void get1() { cout << \n enter the value for b \n .show(). d. Define polymorphism. } }. dc d. Explain the different types of polymorphism. class dc : public bc1.{ protected: int b. } }.get1(). Polymorphism . d.get(). cin>>b. public. d. } 3. public bc2 { public : void show() { cout << The values of a and b are . Example: #include #include class base { public: void show() { cout << \n This is a base class\n . class derived : public base { public: void show() . If the binding is done at run time then it is called as run time polymorphism.Run time compile time Or or Dynamic binding static binding Or or late binding early binding Virtual fuctions operator overloading function overloading Linking a function call to the function definition is called as binding. Compile time polymorphism is achieved by using function overloading and operator overloading. then the members appropriate to the base class is called. It is achieved by using virtual functions. } }. If the binding is done at compile time then it is called as compile time polymorphism. VIRTUAL FUNCTIONS: When the same function is used in both the base class and derived class and if a pointer of base class is used to access the members of the derived class . } }. } }. bptr->show(). class derived : public base { public: void show() { cout << \n This is a derived class\n .*bptr. void main() { base b. Example: #include #include class base { public: virtual void show() { cout << \n This is a base class\n . bptr=&b. bptr=&d. getch(). The base class member functions should be preceeded by a keyword virtual. bptr->show().{ cout << \n This is a derived class\n . . derived d. } o/p This is a base class This is a base class This can be overcome by using virtual functions. void main() { base b. The errors that are caused by events beyond the control of the program are called asynchronous exceptions. bptr->show(). it is important that it is identified and dealt with effectively. } o/p This is a base class This is a derived class 4. synchronous exceptions and asynchronous exceptions. When a program encounters an exceptional condition.*bptr. bptr=&d. namely. Errors such as out-of-range index and over flow belong to the synchronous exceptions. ? Inform that an error has occurred (Throw the exception). getch(). The mechanism performs following tasks: ? Find the problem (Hit the exception).} }. access to an array outside of its bounds. Explain multiple catch statement with help of suitable C++ coding. The error handling code basically consists of two segments one to detect errors and to throw exceptions. ? Receive the error information (Catch the expression). Exceptions are of two kinds. The proposed exception handling mechanism is designed to handle only synchronous exceptions. bptr->show(). derived d. Anomalies might include conditions such as division by zero. Exception Handling Mechanism: . EXCEPTION HANDLING Exceptions are run time anomalies or unusual conditions that a program may encounter while executing. ? Take corrective actions (Handle the exceptions). bptr=&b. or running out of memory or disk space. and other to catch the exceptions and to take appropriate actions. throw and catch. it is thrown using a throw statement in the try block. we need to use some devices such as floppy disk or hard disk to store the data. the control goes to the statement immediately after the catch block. The keyword try is used to preface a block of statements which may generate exceptions. Programs can be designed to perform the read and write . namely. A file is a collection of related data stores in a particular area on the disk. FILE To handle large volumes of data. try. The point at which the throw is executed is called the throw point. The data is stored in these devices using the concept of files. we can associate more than one catch statement with a try as shown below: try { // try block } catch(type1 arg) { // catch block1 } catch(type2 arg) { // catch block2 } catch(typeN arg) { // catch blockN } Catch All Exceptions: In some situations we may not be able to anticipate all possible types of exceptions we can force a catch statement to catch all exceptions instead of a certain type alone. In such cases. When no exception is detected and thrown. then catch block is executed for handling the exception. Most often exceptions are thrown by the functions that are invoked from within the try blocks. When an exception is detected. This is achieved as follows: catch ( ) { // statement of processing all exceptions } 5.It is built upon three keywords. and handles it appropriately. If the type of object thrown matches the arg type in the catch statement. This block of statements is known as try block. The general format of code for this kind of relationship is shown below Multiple catch statements: It is possible that a program segment has more than one condition to throw an exception. Describe the various file modes and its syntax. If they do not match the program is aborted with the help of the abort() function is invoked by default. A catch block is defined by the keyword catch catches the exception thrown by the throw statement in the try block. It may contain two parts. This file should be included for performing file operations. ofstream and fstream. The I/O system of C++ uses file stream as an interface b/n the programs and the files.txt Student For opening a file. a primary name and an optional period with extension. Data transfer between the program and a disk file. The second argument will specify the file-mode. 2. These include ifstream. we must create a file stream and then link it to the filename. A program involves either or both of the following kinds of data communication: 1. Examples: Input. The general form of the function open() with two arguments is: stream-object. File Modes: The two methods that we discussed can also take two arguments instead of one. The first method is useful when only one file in the stream is used. There are two ways of opening a file: ? Using the constructor function of the class.open ( filename . In other words. ? Using the member function open() of the class. The second method is useful when multiple files are managed using one stream. Parameter Meaning ios::app Append to end of file ios::ate Go to end of file on opening ios::binary Binary file ios::in Open file for reading only ios::nocreate Open fails if the file does not exist ios::noreplace Open fails if the file already exists ios::out Open file for writing only ios::trunc Delete the contents of the file if it exists File pointers and their manipulations: Each file has two associated pointers known as the file pointers. They are input pointer and output . mode). These classes are contained in the header file fstream. The stream that receives data from the program is known as output stream. The stream that supplies data to the program is known as input stream. Data transfer between the console unit and the program.operations on these files. Classes for File Stream Operations: The I/O system of C++ contains a set of classes that define the file handling methods. the input stream reads data from the file and the output stream writes data to the file. The filename is a string of characters that make up a valid filename for the operating system. The above program will give the number of bytes in the file. moves file pointer to the byte number 10. Read only mode: Input pointer is automatically set at the beginning so that we can read the file from start. The input pointer is used for reading the contents of a given file location and the output pointer is used for writing to a given file location. catch and throw keywords. or running out of memory or disk space. ? Inform that an error has occurred (Throw the exception). The mechanism performs following tasks: ? Find the problem (Hit the exception). The bytes are numbered from zero hence it points to the 11th byte in the file. The errors that are caused by events beyond the control of the program are called asynchronous exceptions.open( filename . namely. namely. since the file is opened in the append mode. Errors such as out-of-range index and over flow belong to the synchronous exceptions. throw and catch. Functions for manipulations of file pointers: seekg() Moves input pointer to a specified location seekp() Moves output pointer to a specified location tellg() Gives the current position of the input pointer tellp() Gives the current position of the output pointer Example: infile.ios::app). Exceptions are run time anomalies or unusual conditions that a program may encounter while executing. The keyword try is used to preface a block of statements which may generate exceptions. This block of . ? Take corrective actions (Handle the exceptions). it is important that it is identified and dealt with effectively.tellp(). Anomalies might include conditions such as division by zero. synchronous exceptions and asynchronous exceptions. access to an array outside of its bounds. int p = out. Write only mode: Existing contents are deleted and the output pointer is set at the beginning. 6.pointer. Discuss the need for exception with try. Exceptions are of two kinds. The proposed exception handling mechanism is designed to handle only synchronous exceptions. Exception Handling Mechanism: It is built upon three keywords. Append mode: The output pointer is set to the end of file. and other to catch the exceptions and to take appropriate actions. When a program encounters an exceptional condition. try. ? Receive the error information (Catch the expression).seekg(10). The error handling code basically consists of two segments one to detect errors and to throw exceptions. ofstream out out. the control goes to the statement immediately after the catch block. The general format of code for this kind of relationship is shown below: Example: #include void divide(int a. } . it is thrown using a throw statement in the try block. If the type of object thrown matches the arg type in the catch statement. The point at which the throw is executed is called the throw point. and handles it appropriately. else throw(b). A catch block is defined by the keyword catch catches the exception thrown by the throw statement in the try block. When no exception is detected and thrown. int x.y. then catch block is executed for handling the exception. Most often exceptions are thrown by the functions that are invoked from within the try blocks. When an exception is detected.statements is known as try block. If they do not match the program is aborted with the help of the abort() function is invoked by default. } catch(int i) { cout << Error! Dividing by Zero .y). cin >> x >> y. int b) { if(b!=0) cout << Result = << a/b. try { divide(x. } void main() { cout << Enter two numbers . Single level inheritance 2. Multiple inheritance 3. diagram: refer diagram at pg 193 in E. Example : #include #include class bc1 { protected: int a. Hierarchical inheritance Multiple inheritance: It is a type of inheritance in which a class can inherit properties from more than one class. Balaguruswamy. Syntax: Class derivedclass name : visibility mode baseclass1. Multilevel inheritance 4. . It provides the concept of reusability By inheritance some or all the properties of a class can be derived in to another class. Hybrid inheritance and 5. The class which provides the properties is called as base class and the class which derives the properties is called as derived class. Explain the various forms of inheritance in C++ with necessary coding. INHERITANCE: Inheritance is a mechanism of deriving a new class from a old class. }.visibilitmode baseclass2 { body of the derived class. visibility mode can be either private or public. Types: There are five types of inheritance viz 1.7. } }. } }. public bc2 { public : void show() { cout << The values of a and b are . cin>>b.public : void get() { cout << \n enter the value for a\n . class bc2 { protected: int b. d.show(). d. d. dc d. } }. } output: Enter the value for a 20 . cin >>a.get(). class dc : public bc1. void get1() { cout << \n enter the value for b \n . cout <<a<< \n <<b.get1(). public. void main() { clrscr(). UNIT III DATA STRUCTURES & ALGORITHMS Algorithm. Heaps hashinghash tables without linked lists 1. Priority queues-Binary Heap-Application. Analysis. . Write down the definition of data structures? A data structure is a mathematical or logical way of organizing data in the memory that consider not only the items stored but also the relationship to each other and also it is characterized by accessing functions. Stacks and queues.Enter the value for b 30 The values of a and b are 20 30 . Lists. Objects such as list. produce the corresponding output and terminate in a finite time. It consist of set of finite steps which.ADT refers to the basic mathematical concept that defines the datatype. Define Algorithm? Algorithm is a solution to a problem independent of programming language. What are the operations of ADT? Union. Eg. Intersection. 7. A useful tool for specifying the logical properties of a datatype is the abstract data type. Give few examples for data structures? Stacks. What is meant by an abstract data type (ADT)? An ADT is a set of operation. Linked list. 4. .2. set and graph along their operations can be viewed as ADT's. graphs 3. Trees. What are the features of an efficient algorithm? Free of ambiguity Efficient in execution time Concise and compact Completeness Definiteness Finiteness 5. size. complement and find are the various operations of ADT. Queue. when carried out for a given set of inputs. List down any four applications of data structures? Compiler design Operating System Database Management system Network analysis 6. Operations on Rational number: Creation of rational number from two integers.. a3. . ai+1 the successor of ai and ai-1 is the predecessor of ai. Any element in the list at the position I is defined to be ai. General list of the form a1. Addition Multiplication Testing for equality.What is a Rational number? A Rational number is a number that can be expressed as the quotient of two integers.A sequence S is sometimes written as the enumeration of its elements. What is meant by list ADT? List ADT is a sequential storage structure.then length of S is n. an and the size of the list is 'n'.8. What are the various operations done under list ADT? Print list Insert Make empty Remove Next Previous Find kth 10. . What are the two parts of ADT? Value definition Operator definition 12.such as S= If S contains n elements. What is a Sequence? A sequence is simply an ordered set of elements. a2. 9. 11. Pointer is basically a number. Define Structure? A Structure is a group of items in which each item is identified by its own identifier .each of which is known as a member of the structure.last(S). and an element x. 16. 18.char and double 15.an index. first(S) returns the value of the first element of S last(S) returns the value of the last element of S nilseq :Sequence of length 0 is nilseq . What are the two basic operations that access an array? Extraction: Extraction operation is a function that accepts an array. Define len(S).. What are the two things specified in declaration of variables in C? It specifies the amount of storage that must be set aside for objects declared with that type. 17.and returns an element of the array. a .nilseq ? len(S) is the length of the sequence S.first(S). What is a pointer? Pointer is a variable. What is an array ? Array may be defined abstractly as a finite ordered set of homogenous elements. 19.13.float. a . How data represented by strings of bits are to be interpreted.Finite means there is a specific number of elements in the array. 14. which stores the address of the next element in the list. Storing: Storing operation accepts an array .an index i .ie. What are the four basic data types? int. .i. contains no element. 8.2. What is a Fibonacci sequence? Fibonacci sequence is the number of integers 0.13. . 23. Each element in this sequence is the sum of the two preceding elements. What are the two operations of Stack? _ PUSH _ POP 24.34.1. 24. 22. 23. 21.3. Define Recursion? Recursion is a function calling itself again and again.20. External variables are variables that are declared outside any function and are allocated storage at the point at which they are first encountered for the remeinder of the program s execution. Define Union ? Union is collection of Structures . What is a Stack? A Stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one end.which permits a variable to be interpreted in several different ways. Define Automatic and External variables? Automatic variables are variables that are allocated storage when the function is invoked.5. called the top of the stack. What is a Queue? A Queue is an ordered collection of items from which items may be deleted at .1.21. The other name of stack is Last-in -First-out list. Write postfix from of the expression A+B-C+D? A-B+C-D+ 25. there will be two pointers one to point the next element and the other to point the previous element location.one end called the front of the queue and into which tems may be inserted at the other end called rear of the queue.Queue is called as First in-FirstOut(FIFO). 32.Name the three fields of Doubly Linked list? Info field Left field Right field . 26. What is a doubly linked list? In a simple linked list. What are the different ways to implement list? Simple array implementation of list Linked list implementation of list 28. What are the advantages in the array implementation of list? a) Print list operation can be carried out at the linear time b) Find Kth operation takes a constant time 29. there will be one pointer named as 'NEXT POINTER' to point the next element. which are not necessarily adjacent in memory. 30. What is a linked list? Linked list is a kind of series of data structures. What is a Priority Queue? Priority queue is a data structure in which the intrinsic ordering of the elements does determine the results of its basic operations. 27. where as in a doubly linked list. Each structure contain the element and a pointer to a record containing its successor.Name the two fields of Linked list? Info field Next field 31. Ascending and Descending priority queue are the two types of Priority queue. In the case of array implementation of queue. List three examples that uses linked list? Polynomial ADT Radix sort Multi lists 36. Write postfix from of the expression A+B-C+D? A-B+C-D 38. Explain the usage of stack in recursive algorithm implementation? In recursive algorithms. Define double circularly linked list? In a doubly linked list. 35. Give some examples for linear data structures? Stack Queue 37. the condition to be checked for an empty queue is READ<front. we have to check whether READ=HEAD where REAR is a pointer pointing to the last node in a queue and HEAD is a pointer that pointer to the dummy header.33. point to the first element of the list.then it is a circularly linked list. stack data structures is used to store the return address when a recursive call is . 39. 34. What is the need for the header? Header of the linked list is the first element in the list and it stores the number of elements in the list. What are the postfix and prefix forms of the expression? A+B*(C-D)/(P-R) Postfix form: ABCD-*PR-/+ Prefix form: +A/*B-CD-PR 40. if the last node or pointer of the list. How do you test for an empty queue? To test for an empty queue. It points to the first data element of the list. How do you analyses an algorithm? . Define max heap? A heap in which the parent has a larger key than the child's is called a max heap. 42. The operations that can be done with queue are insert and remove. 44. which wraps around upon reaching the end of the array is called as circular queue. 43. PART B 1. Define min heap? A heap in which the parent has a smaller key than the child is called a min heap.encountered and also to store the values of all the parameters essential to the current state of the procedure.in -first out list. Write down the operations that can be done with queue data structure? Queue is a first . 41. What is a circular queue? The queue. because clock-time can vary based on many things. memory space.Algorithm analysis refers to the process of determining how much computing time and storage that algorithms will require.) needed by each algorithm. it is difficult to use actual clock-time as a consistent measure of an algorithm s efficiency. This can show how an algorithm s efficiency changes according to the size of the input. Space Complexity: Determine the approximate memory required to solve a problem of size n. The main resources are: Running Time Memory Usage Communication Bandwidth Running time is usually treated as the most important since computational time is the most precious resource in most problem domains. there are many possible algorithms. However. rather than according to an absolute amount of time involved. One has to be able to choose the best algorithm for the problem at hand using some scientific method. we can analyze an algorithm according to the number of operations required. For example. There are two approaches to measure the efficiency of algorithms: Empirical: Programming competing algorithms and trying them on different instances. In other words. To classify some data structures and algorithms as good. we need precise ways of analyzing them in terms of resource requirement. Theoretical: Determining the quantity of resources required mathematically (Execution time. it s a process of predicting the resource requirement of algorithms in a given environment. Complexity Analysis Complexity Analysis is the systematic study of the cost of computation. In order to solve a problem. etc. Specific processor speed Current processor load Specific data for a particular run of the program o Input Size o Input Properties Operating Environment Accordingly. The goal is to have a meaningful measure that permits comparison of algorithms independent of operating platform. Complexity analysis involves two distinct phases: Algorithm Analysis: Analysis of the algorithm or data structure to produce a function T (n) that . measured either in time units or in operations performed. There are two things to consider: Time Complexity: Determine the approximate number of operations required to solve a problem of size n. or in the amount of storage space required. 4. We assume an arbitrary time unit. Order of Magnitude Analysis: Analysis of the function T (n) to determine the general complexity category to which it belongs. Always assume that the loop executes the maximum number of iterations possible. In the for loop: 1 assignment.i<n. Execution of one of the following operations takes time 1: Assignment Operation Single Input/Output Operation Single Boolean Operations Single Arithmetic Operations Function Return 3. Examples: 1. 2. cin>>n. n+1 tests. However. There is no generally accepted set of rules for algorithm analysis. For nested loops. int count(){ int k=0. return 0.i++) k=k+1. Running time of a function call is 1 for setup + the time for any parameter calculations + the time required for the execution of the function body.describes the algorithm in terms of the operations performed in order to measure the complexity of the algorithm. and an addition. and n increments. cout<< Enter an integer . Analysis Rules: 1. analyze inside out. switch) is the time for the condition evaluation + the maximum of the running times for the individual clauses in the selection. 1 for the input statement.} Time Units to Compute ------------------------------------------------1 for the assignment statement: int k=0 1 for the output statement. for (i=0. an exact count of operations is commonly used. . Loops: Running time for a loop is equal to the running time for the statements inside the loop * number of iterations. Running time of a selection statement (if. 5. n loops of 2 units for an assignment. The total running time of a statement inside a group of nested loops is the running time of the statements multiplied by the product of the sizes of all the loops. ------------------------------------------------------------------T (n)= 1+1+1+(1+n+1+n)+2n+1 = 4n+6 = O(n) 2. i++. void func() { int x=0. 1 for the second assignment statement: i=0. cout<< Enter an Integer value . } while (j<n) { j++. and an addition.i++) sum=sum+1. int total(int n) { int sum=0. n loops of 2 units for an assignment. for (int i=1. and n increments. } Time Units to Compute ------------------------------------------------1 for the assignment statement: int sum=0 In the for loop: 1 assignment. return sum.i<=n. ------------------------------------------------------------------T (n)= 1+ (1+n+1+n)+2n+1 = 4n+4 = O(n) 3. cin>>n. n+1 tests. while (i<n){ x++. int i=0. } } Time Units to Compute ------------------------------------------------1 for the first assignment statement: x=0.1 for the return statement. int j=1. 1 for the return statement. . 1 for the input statement. loop control. an addition. return partial_sum. a for loop translates to a summation. i <= n. For Loops: Formally In general. In the first while loop: n+1 tests n loops of 2 units for the two increment (addition) operations In the second while loop: n tests n-1 increments ------------------------------------------------------------------T (n)= 1+1+1+1+1+n+1+2n+n+n-1 = 5n+5 = O(n) 4. 1 for the output statement. n+1 tests. i++) partial_sum = partial_sum +(i * i * i). } Time Units to Compute ------------------------------------------------1 for the assignment. for (int i = 1. it can be simplified by using some formal approach in which case we can ignore initializations. 1 for the return statement. . ------------------------------------------------------------------T (n)= 1+(1+n+1+n)+4n+1 = 6n+4 = O(n) Formal Approach to Analysis In the above examples we have seen that analysis so complex. int sum (int n) { int partial_sum = 0. hence N additions in total. There is 1 addition per iteration of the loop. Suppose we count the number of additions that are done. However. 1 assignment. and n increments.1 for the third assignment statement: j=1. n loops of 4 units for an assignment. and two multiplications. The index and bounds of the summation are the same as the index and bounds of the for loop. and book keeping. Here we have given the structure of a typical node: struct node { char name[20]. The last node has a link to the special value NULL. to show that it is the last link in the chain. 2. Consecutive Statements: Formally Add the running times of the separate blocks of your code Conditionals: Formally If (test) s1 else s2: Compute the maximum of the running time for s1 and s2. most importantly. each with a link to the next node in the series. which points to the first link in the chain so that we can keep track of it. called Start (also called head). Again. // In metres node *nxt. address. Defining the data structure for a linked list The key part of a linked list is a structure.// Pointer to next node }. It forms a chain of "nodes" with pointers representing the links of the chain and holding the entire thing together. A linked list can be represented by a diagram like this one: This linked list has four nodes in it. a pointer to the next node. Explain how pointer are used to implement linked list structure. one for each for loop. and. This gives a pointer to the next node in the list. The outer summation is for the outer for loop. age or whatever for the items in the list).Nested Loops: Formally Nested for loops translate into multiple summations. count the number of additions. // Name of up to 20 letters int age float height. which holds the data for each node (the name. The important part of the structure is the line before the closing curly brackets. which any pointer (whatever its type) can point to. There is also another special pointer. struct node *start_ptr = NULL. This is the only case in C++ where you are allowed to refer to a data type (in . A linked list is a data structure that is built from structures and pointers. The reason we needed a start pointer in the ordinary linked list is because.this case node) before you have even finished defining it! We have also declared a pointer called start_ptr that will permanently point to the start of the list. so without the start pointer. Explain various operation performed on the doubly linked list. Instead. one to the next node and one to the previous one . It gives the following situation: We still need to consider the directions 'forward' and 'backward'. there is simply a pointer to some position in the list that can be moved left or right. then it shouldn't be much of a leap to doubly linked lists A doubly linked list is one where there are links from each node in both directions: You will notice that each node in the list has two pointers. // Pointer to next node node *prv. having moved on from one node to another.again. 3. we can move the current pointer backwards and forwards at will. Creating Doubly Linked Lists The nodes for a doubly linked list would be defined as follows: struct node{ char name[20]. if you've mastered how to do singly linked lists. current = new node. We have also included some code to declare the first node and set its pointers to NULL. // Pointer to previous node }. node *nxt. the ends of the list are defined by NULL pointers. Also there is no pointer to the start of the list. To start with. current->prv = NULL. we can't easily move back. Doubly Linked Lists That sounds even harder than a linked list! Well. node *current. there are no nodes in the list. so in this case. which is why start_ptr is set to NULL. we would lose track of all the nodes in the list that we have already passed. current->nxt = NULL. With the doubly linked list. we will need to define functions to add a node to the start of the list (left-most position) and the end of the list (right-most position). current->name = "Fred". Adding a Node to a Doubly Linked List . } Here. while (temp->prv != NULL) temp = temp->prv. } void add_node_at_end () { // Declare a temporary pointer and move it to the end node *temp = current. Linked List Implementation of Stacks: the PUSH operation . a temporary pointer is set up and is made to march along the list until it points to last node in the list. Firstly. We'll go through the function for adding a node to the right-most end of the list. the new name is passed to the appropriate function as a parameter. while (temp->nxt != NULL) temp = temp->nxt. Give linked list implementation of stack operation. 4. a new node is declared. // Store the new name in the node temp2->nxt = NULL. and the name is copied into it. // This is the new start of the list temp2->prv = temp. // Links to current list temp->nxt = temp2. temp2->name = new_name. // Declare a new node and link it in node *temp2.void add_node_at_start (string new_name) { // Declare a temporary pointer and move it to the start node *temp = current. temp2 = new node. The nxt pointer of this new node is set to NULL to indicate that this node will be the new end of the list. // This is the new start of the list temp2->nxt = temp. After that. // Store the new name in the node temp2->prv = NULL. The method is similar for adding a node at the other end. // Links to current list temp->prv = temp2. temp2->name = new_name. temp2 = new node. The prv pointer of the new node is linked into the last node of the existing list. // Declare a new node and link it in node *temp2. The nxt pointer of the current end of the list is set to the new node. Here. delval. struct node *next. free the TOP most element. Linked List Implementation of Stacks: the POP Operation This is again very similar to the deletion operation in any Linked List. Algorithm: Step-1: If the Stack is empty then give an alert message "Stack Underflow" and quit. the TOP most element will be deleted and "target" will be made as the TOP most element. /*stack is initially empty*/ struct node *top = stack.. Supposing you have only one element left in the Stack. but you can only delete from the end of the list and only one at a time. we'll have a list pointer. } struct node *stack = NULL. main() { int newvalue. "target". In step[2] we freed the TOP most element. Since a dynamic list is used for the stack. means it has no prior upper limit set. make "target" as your TOP most element Implementation: struct node { int nodeval. The only difference is that here you'll add the new element only at the end of the list.. which will be pointing to the last but one element in the List (stack). and that makes it a stack.It s very similar to the insertion operation in a dynamic singly linked list. which means addition can happen only from the TOP. In step[1] we got the "target" pointing to the last but one node. "top" and "bottom" pointers point to NULL and quit Step-4: Make "target" point to just one element before the TOP. we don't have to check for the Overflow condition at all! In Step [1] we create the new element to be pushed to the Stack. In step[3] we made the "target" node as our TOP most element. Every time we POP. which is our newly added element. See how. In Step [3] the TOP is moved and made to point to the last element in the stack. So. or else proceed Step-2: If there is only one element left go to step-3 or else step-4 Step-3: Free that element and make the "stack". In Step [2] the TOP most element is made to point to our newly created element. . then we won't make use of "target" rather we'll take help of our "bottom" pointer. the Stack is also dynamic. .. push(newvalue); .. delval = pop(); /*POP returns the deleted value from the stack*/ } int pop( ) { int pop_val = 0; struct node *target = stack; if(stack == NULL) /*step-1*/ cout<<"Stack Underflow"; else { if(top == bottom) /*step-2*/ { pop_val = top -> nodeval; /*step-3*/ delete top; stack = NULL; top = bottom = stack; } else /*step-4*/ { while(target->next != top) target = target ->next; pop_val = top->nodeval; delete top; top = target; target ->next = NULL; } } return(pop_val); } 5. What is a stack? Explain any two operations performed on a stack with required algorithm. Stacks A simple data structure in which insertion and deletion occur at the same end, is termed (called) a stack. It is a LIFO (Last In First Out) structure. The operations of insertion and deletion are called PUSH and POP Push - push (put) item onto stack Pop - pop (get) item from stack Initial Stack Push(8) Pop TOS=> 4 1 3 6 TOS=> 8 4 1 3 6 TOS=> 4 1 3 6 Our Purpose: To develop a stack implementation that does not tie us to a particular data type or to a particular implementation. Implementation: Stacks can be implemented both as an array (contiguous list) and as a linked list. We want a set of operations that will work with either type of implementation: i.e. the method of implementation is hidden and can be changed without affecting the programs that use them. The Basic Operations: Push() { if there is room { put an item on the top of the stack else give an error message } } Pop() { if stack not empty { return the value of the top item remove the top item from the stack } else { give an error message } } CreateStack() { remove existing items from the stack initialise the stack to empty } Array Implementation of Stacks: The PUSH operation Here, as you might have noticed, addition of an element is known as the PUSH operation. So, if an array is given to you, which is supposed to act as a STACK, you know that it has to be a STATIC Stack; meaning, data will overflow if you cross the upper limit of the array. So, keep this in mind. Algorithm: Step-1: Increment the Stack TOP by 1. Check whether it is always less than the Upper Limit of the stack. If it is less than the Upper Limit go to step-2 else report -"Stack Overflow" Step-2: Put the new element at the position pointed by the TOP Implementation: static int stack[UPPERLIMIT]; } push(int item) { top = top + 1. . "Stack underflow". if an attempt is made to Pop an item from an empty Stack. ...In array implementation. . /*stack is empty*/ . if you're taking an array as the stack. int top=-1. or else go to step-2 Step-2: a) Hold the value for the element pointed by the TOP b) Put a NULL value instead c) Decrement the TOP by 1 Implementation: static int stack[UPPPERLIMIT]. Array Implementation of Stacks: the POP operation POP is the synonym for delete when it comes to Stack. . Algorithm Step-1: If the Stack is empty then give the alert "Stack underflow" and quit. remember that you'll return an error message. . /*step-1 & 2*/ else cout<<"Stack Overflow". main() { ... } Note:.. .. push(item). . So.we have taken TOP = -1 to signify the empty stack. ..... . ..int top= -1. main() { . if(top < UPPERLIMIT) stack[top] = item. as this simplifies the implementation. OK.. poped_val = pop(). push(item).Step-2:(b) signifies that the respective element has been deleted. top = top -1. } push(int item) { if(stack == NULL) /*step-1*/ { newnode = new node /*step-2*/ newnode -> item = item. /*stack is initially empty*/ struct node *top = stack. } return(del_val). newnode -> next = NULL. struct node *next. main() { . . } Note: . . /*step-2*/ stack[top] = NULL.. /*step-1*/ else { del_val = stack[top]. if(top == -1) cout<<"Stack underflow". } struct node *stack = NULL. Algorithm Step-1: If the Stack is empty go to step-2 or else go to step-3 Step-2: Create the new element and make your "stack" and "top" pointers point to it and quit.} int pop() { int del_val = 0. Implementation: struct node{ int item.. Step-3: Create the new element and make the last (top most) element of the stack to point to it Step-4: Make that new element your TOP most element by making the "top" pointer point to it. .. top = stack. Dequeue().Dequeue operation deletes data having highest priority in the list .deletes Aster Dequeue(). State and explain the priority queue with example. newnode -> next = NULL.stack = newnode. top ->next = newnode.deletes Meron Now the queue has data having equal priority and dequeue operation deletes the front element like in the case of ordinary queues. /*step-3*/ newnode -> item = item. top = newnode. Dequeue().is a queue where each data has an associated key that is provided at the time of insertion.deletes Alemu .deletes Abebe Dequeue().One of the previously used dequeue or enqueue operations has to be modified Example: Consider the following queue of persons where females have higher priority than males (gender is the key to give priority). . } else { newnode = new node. Priority Queue . /*step-4*/ } } 6. insert the deleted value in the array in its proper position. 3. Heap tree is a binary tree in which each node has a value greater than both its children (if any). Heap Sort Heap sort operates by first converting the list in to a heap tree. The time complexity of heap sort is O(nlogn). Construct a binary tree The root node corresponds to Data[0]. <a<< \n <<b. Construct the heap tree from initial binary tree using "adjust" process. right most value. Explain. then the left child of this node corresponds to the element with index 2*i+1 and the right child corresponds to the element with index 2*i+2. in the above example the implementation of the dequeue operation need to be modified. If any or both of these elements do not exist in the array. <n. then the corresponding child node does not exist either. It uses a process called "adjust to accomplish its task (building a heap tree) whenever a value is larger than its parent. Sort by swapping the root value with the lowest. If we consider the index associated with a particular node to be i. <front. with example the basic heap operations and write the algorithms for the same. <a<< \n <<b. What are the various method involved to solve hashing function? 8. . adjust the heap tree. 7. Example: Sort the following list using heap sort algorithm. right most value and deleting the lowest.b).Thus. and repeat this process until the tree is empty. 2. 5824139760 <a. right most value and inserting the deleted value in the array in it proper position. Algorithm: 1. <div(a.i++) <n){ <n) Swap the root node with the lowest. right most node and delete the lowest. . . Introduction to NP . PART A 1.completeness. that each node is visited only once.UNIT 4 NONLINEAR DATA STRUCTURES Trees-Binary trees. Define tree? A tree is a data structure. Define non-linear data structure? Data structure which is capable of expressing more complex relationship than that of physical adjacency is called non-linear data structure. What are the applications of binary tree? Binary tree is used in data processing. What is meant by traversing? Traversing a tree means processing it in such a way. Graph Algorithms-Topological sort. 3. What are the different types of traversing? The different types of traversing are . The other two subsets are themselves binary trees called the left and right sub trees. a. search tree ADT. 7. 4. The first subset contains a single element called the root of the tree. shortest path algorithm network flow problems-minimum spanning tree . 2. Define leaf? In a directed tree any node which has out degree o is called a terminal node or a leaf. AVL trees. Hierarchical database management system 6. which represents hierarchical relationship between individual Data items. 5. File index schemes b. What is a Binary tree? A Binary tree is a finite set of elements that is either empty or is partitioned into three disjoint subsets. Breadth first search b. 11. 14. What are the two traversal strategies used in traversing a graph? a. b. 8. Post-order traversal-yields postfix from of expression. What are the two methods of binary tree implementation? Two methods to implement a binary tree are. a set E which is the set of edges of the graph. Adjacency matrix b. c. . Linear representation. 10.a. For Example. b. Adjacency list 12.v) where u. a. Pre-order traversal-yields prefix from of expression. Define Graph? A graph G consist of a nonempty set V which is a set of nodes of the graph. Depth first search 13. E).Name the different ways of representing a graph? a. if and edge xÎE is associated with a pair of nodes (u. In-order traversal-yields infix form of expression. Give some example of NP complete problems. Linked representation 9. then we say that the edge x connects the nodes u and v. What is an acyclic graph? A simple diagram which does not have any cycles is called an acyclic graph. It can also be represented as G=(V. Define adjacent nodes? Any two nodes which are connected by an edge in a graph are called adjacent nodes. and a mapping from the set for edge E to a set of pairs of elements of V. v Î V. v4. 12. UNIT 5 SORTING AND SEARCHING Sorting Insertion sort. Dynamic Programming (All pairs Shortest Path Problem).v2. (8) (April/May 2007) 8. Merge sort. What is single source shortest path problem? Discuss Dijkstra s single source shortest path algorithm with an example.? Hamiltonian circuit.v3. Indirect sorting. (8) (April/May 2007) 10. Heap sort. Write an algorithm to find the minimum cost spanning tree of an undirected weighted graph. Explain depth first search on a graph with necessary data structures. Write suitable ADT operation for shortest path problem. Explain Depth first & Breadth First Traversal algorithms. Explain the topological sort algorithm. Discuss and write the program to perform topological sorting. How do you construct a minimum cost spanning tree with Prim s algorithm? (8) (April/May 2008) 6. Quick sort. (May/June 2007) 2. Find the shortes path between v1. 11. (8) (May/June 2007) 3.v6 & v7. (8) (April/May 2008) 7. Show the simulation of shortest path with an example graph. PART A .v5. Introduction to Algorithm Design Techniques Greedy algorithm (Minimum Spanning Tree). Explain Prim s algorithm with an example. (8) (April/May 2007) 9. Shell sort. Divide and Conquer (Merge Sort). Write ADT operation for Prim s Algorithm. Explain Dijkstra s algorithm using the following graph. Explain Kruskal s algorithm with an example. (April/May 2008) 5. ? Travelling salesmen problems ? Longest path problems ? Bin packing ? Knapsack problem ? Graph colouring problem PART B 1. (8) (May/June 2007) 4. Bucket sort. What is dynamic programming? (April/May 2006) ********* 1. External sorting 3. 12. Internal sorting b. What is the basic idea of shell sort? 8. Give an example for each. What are the various factors to be considered in deciding a sorting algorithm? 6. 15. What is the average efficiency of heap sort? 11. What is the purpose of quick sort? 9. 16. Define time complexity. What is meant by sorting? Ordering the data in an increasing or decreasing fashion according to some relationship among the data item is called sorting. What are the two main classifications of sorting based on the source of data? a.1. 20. What is the advantage of quick sort? 10. What are the two main classifications of sorting based on the source of data? 3. average case & worst case of an algorithm. What is meant by external sorting? 4. Define space complexity. . 18. What does asymptotic notation mean? 17. Define Algorithm. What is performance analysis of an algorithm? 14. 2. What is divide and conquer technique? 19. What is meant by sorting? 2. Define Greedy algorithm. What is complexity analysis? 13. Define best case. What is meant by internal sorting? 5. What is meant by external sorting? External sorting is a process of sorting in which large blocks of data stored in storage Devices are moved to the main memory and then sorted. What is the main idea behind insertion sort? 7. 8. 5. 10. 12. n is the number of elements sorted. What is the main idea in Bubble sort? The basic idea underlying the bubble sort is to pass through the file sequentially Several times. The algorithm forms a base for program. What is meant by internal sorting? Internal sorting is a process of sorting the data in the main memory. just enough for to reach its final place in the array. in one move. An algorithm is clearly specified set of simple instructions to be followed to solve a problem. What is the average efficiency of heap sort? The average efficiency of heap sort is 0 (n(log2 n)) where. Define Algorithm. 9. it is first divide the array into smaller segments. Programming time b. What are the various factors to be considered in deciding a sorting algorithm? a. What is the purpose of quick sort? The purpose of the quick sort is to move a data item in the correct direction. 7. Memory needed for program environment 6. What is the advantage of quick sort? Quick sort reduces unnecessary swaps and moves an item to a greater distance. which are then separately sorted using the insertion sort. 11. Execution time of the program c. What is the basic idea of shell sort? Instead of sorting the entire array at once. Each pass consists of comparing each element in the file with its successor (x[i] and x[i+1] and interchanging the two elements if they are not in proper order.4. What is complexity analysis? . Define best case of an algorithm. Define time complexity. Posterior Testing 14. It is the shortest time that an algorithm will use over all instances of size n for a given problem to produce the result. . 17. 16. What does asymptotic notation mean? Asymptotic notations are terminology that is introduced to enable us to make meaningful statements about the time and space complexity of an algorithm. Priori estimates b.It is the analysis of the amount of memory and time an algorithm requires to completion. 15. Time complexity is the amount of computer time an algorithm requires to run to completion. What is performance analysis of an algorithm? The analysis of the performance of an algorithm based on specification is called performance analysis. There are two types of Complexity Space Complexity Time Complexity 13. Define space complexity. The different notations are Big Oh notation Omega notation Theta notation. Space complexity of an algorithm is the amount of memory it needs to run to completion. It is loosely divided into a. PART B 1. Discuss the various notations and their complexities. What is divide and conquer technique? Divide and Conquer algorithm is based on dividing the problem to be solved into several. worst case time complexity of a linear search. 10. 2. At each stage. Explain the various notations used in the analysis of algorithms. Explain divide & conquer technique with a suitable example. a decision is made regarding whether a particular input is an optimal solution. 6. smaller sub instances. 4. (May/June 2007) 7. (8) (April/May 2008) 8. Explain dynamic programming with a suitable example. Write a short note on analysis of algorithm. State and explain the algorithm to perform heap sort. Define Greedy method.18. What is dynamic programming? Dynamic programming algorithm is a general class of algorithms which solve problems by solving smaller versions of the problem. Write quick sort algorithm and explain. An example for solution using greedy method is knapsack problem . average. explain how you will measure the efficiency of an algorithm. 3. Explain any two algorithm design techniques with suitable examples. solving them independently and then combining the sub instances solutions so as to yield a solution for the original instance. 20. State and explain the huffman s algorithm . Derive the best. 19. saving the solutions to the small problems and then combining them to solve the larger problems. The greedy method suggests that one can devise an algorithm that works in stages. 5. 9. considering one input at a time. With an example.
Copyright © 2024 DOKUMEN.SITE Inc.