CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 0 ] About These Slides
|
|
- Aubrey Ward
- 5 years ago
- Views:
Transcription
1 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 0 ] About These Slides These slides were developed by Prof. Jennifer Welch Department of Computer Science Texas A&M University College Station, TX welch@cs.tamu.edu during Spring Comments and suggestions for improvements are welcome.
2 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 1 ] What are Data Structures? Data structures are ways to organize data (information). Examples: simple variables objects arrays linked lists Typically, algorithms go with the data structures to manipulate the data (e.g., the methods of a class). This course will cover some more complicated data structures: how what
3 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 2 ] Abstract Data Types An abstract data type (ADT) defines Similar to a This course will cover specifications of pros and cons of how the
4 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 3 ] Specific ADTs The ADTs to be studied (and some sample applications) are:
5 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 4 ] How Does C Fit In? Although data structures are universal (can be implemented in any programming language), this course will use Java and C: We will learn how to gain the advantages of Reasons to learn C: learn useful ubiquitous and Unix C code can be very very efficient
6 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 5 ] Other Topics Course will emphasize good software development practice: Course will touch on several more advanced computer science topics that appear later in the curriculum, and fit in with our topics this semester:
7 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 6 ] Principles of Computer Science Computer Science is like: engineering: science: math: However, CS studies Recurring concepts in computer science are: layers, hierarchies, information-hiding, abstraction, interfaces efficiency, tradeoffs, resource usage reliability, affordability, correctness
8 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 7 ] Introduction to Data Structures Data structures are one of the enduring principles in computer science. Why? 1. Data structures are based on the notion of information hiding: 2. A number of data structures are useful in a wide range of applications.
9 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 8 ] Efficiency Considerations Since these data structures are so widespread, it s important to implement them efficiently. Measures of efficiency: in We will study tradeoffs, such as Efficiency will be measured using
10 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 9 ] Asymptotic Analysis Actual (wall-clock) time of a program is affected by: Instead of wall-clock time, look at the pattern of the program s behavior as the problem size increases. This is called asymptotic analysis.
11 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 10 ] Big-Oh Notation Big-oh notation is used to capture the generic From a practical point of view, you can get the big-oh notation for a function by Which terms are lower order than others? In increasing order: Examples: 4302 = n 3 + n log n + n 5 + n = 34n 3, 2n log n + :0004n 5 +5:2n= See Appendix B, Section 4 of Standish, or CPSC 311, for mathematical definitions and justifications.
12 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 11 ] Why Multiplicative Constants are Unimportant An example showing how multiplicative constants become unimportant as n gets very large: n 1000 log n :0001 n ,384 32,768 1,048,576 Big-oh notation is not always appropriate! If your program is working on small input sizes,
13 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 12 ] Generic Steps How can you figure out the running time of an algorithm without implementing it, running it on various inputs, plotting the results, and fitting a curve to the data? And even if you did that, how would you know you fit the right curve? We count generic steps of the algorithm. Each generic step that we count should be Classifying an assignment statement as a generic step is Classifying a statement sort the entire array as a generic step is
14 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 13 ] Stack vs. Heap Memory used by an executing program is partitioned: the stack: When a method begins executing, a piece of the stack (stack frame) is devoted to it. There is an entry in the stack frame for For variables of primitive type, the data itself is stored For variables of object type, When the method finishes, the method s stack frame is the heap: Dynamically allocated memory goes here, including the actual data for objects. Lifetime is
15 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 14 ] Stack Frames Example q p p main main main main calls p p calls q s r r p p p main main main q returns p calls r r calls s r p p main main main s returns r returns p returns
16 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 15 ] Objects An object is an entity (e.g., a ball) that has state behavior A class is the Analogy: a class is like an an object is like an class defines important construction is required to many objects/houses can be created
17 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 16 ] Data Abstraction The class concept supports Similar principles apply as for procedural abstraction: group group separate the issue of separate the issue of
18 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 17 ] References The class of an object is its Objects are declared differently than are variables of primitive types. Suppose there is a class called Person. int total; Person neighbor; Declaration of total allocates storage on the Declaration of neighbor allocates storage on the
19 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 18 ] Creating Objects A constructor is a special method of the class that When a constructor is called, storage space is allocated each object gets the object s state is The name of the constructor for class X is X(). Ex: neighbor = new Person(); The operator new must be put in front of the call to the constructor. Summary: Declaring a variable of an object type produces
20 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 19 ] Creating Objects (cont d) You can combine the declaration and initialization: Person neighbor = new Person(); just as you can for primitive types: int total = 25;
21 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 20 ] Object Assignment & Aliases The meaning of assignment is different for objects than it is for primitive types. int num1 = 5; int num2 = 12; num2 = num1; At the end, num2 holds 5. Person neighbor = new Person(); // creates object 1 Person friend = new Person(); // creates object 2 friend = neighbor; At the end, friend and neighbor both refer to object1(theyarealiases of each other) and nothing refers to object 2 (it is inaccessible).
22 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 21 ] Data Abstraction Revisited As a rule of thumb, referring to instance variables outside the class is For instance, the implementor of the Person class might decide to store the age In this case, getageinyears must change: Code that got the age using this method need not change, but code that got the age using.age directly Moral:
23 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 22 ] Public vs. Private You can tailor the ability to access methods and variables from outside the class, using visibility modifiers. public: the variable or method can private: the variable or method can Visibility modifiers go at the beginning of the line that declares the variable or method. Ex: public static void main(... private int age; Rules of thumb: make instance variables make instance methods that are part of the public interface of the class make instance methods that help with internal work of a class
24 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 23 ] Public vs. Private (cont d) Instance variables should be accessible only indirectly via public get and set methods. Ex: getageinyears() Group together all the private variables/methods, and all the public ones when you format your program.
25 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 24 ] Specification vs. Implementation Users of a class should rely only on the specification of the class. They are allowed to declare create invoke Implementors of a class should define hide protect feel free to
26 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 25 ] Inheritance Inheritance lets a programmer derive a new class from an existing class. New class can use modify have Thus inheritance promotes software reuse. Itisadefining characteristic of Terminology: Class A is derived from (or, inherits from) another class B A is called subclass or child class. B is called superclass or parent class.
27 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 26 ] Benefits of Inheritance Inheritanceis particularlyuseful inlarge software projects: saves provides supports
28 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 27 ] Costs of Inheritance Usually this disadvantage is outweighed by Once system is working,
29 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 28 ] Inheritance in Java To declare that a class is a subclass of another class: class <child-class> extends <parent-class> {... // define the child-class } child class inherits child class inherits child class does NOT inherit child class does NOT inherit Inherited variables and methods can be used in the child class Inheritance is one-way street!!
30 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 29 ] Protected Visibility private: public: This makes it dangerous to inherit variables, since normally instance variables should not be made accessible outside the class. The solution is protected:
31 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 30 ] Overriding Methods When a child class defines a method with the same name and signature (sequence of parameters) as the parent, the child s version overrides the parent s version. Useful when Polymorphism means that These are not necessarily the same, since a variable can refer to any object whose class is a descendant of the variable s class. When in doubt, draw a memory diagram!
32 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 31 ] Abstract Classes Motivation Consider a database for a veterinarian to keep track of medical and billing information for each patient. Each patient is someone s pet (e.g., dog, bird). Some aspects of the vet s business are independent of the particular species (e.g., billing, owner info). Some aspects depend critically on the species (e.g., the vaccination schedule, diet recommendations). An obvious organization is to have a Note that it does not make sense to create a Pet object The Pet class is used to
33 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 32 ] Rules for Abstract Classes and Methods Only instance methods can be declared Any class with an abstract method must be declared A class may be declared abstract An abstract class cannot A non-abstract subclass of an abstract class must If a subclass of an abstract class does not implement all of the abstract methods that it inherits, then Since an abstract class cannot be instantiated, its variables and methods are not directly used. But they can be
34 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 33 ] Declaring an Interface An interface is an abstract class taken to the extreme. It is like an abstract class in which interface <interface name> { <constant declarations> // public final <abstract method declarations> // public abstract } An interface provides a collection of a collection of For example:
35 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 34 ] Implementing an Interface The syntax for inheriting from (called implementing) an interface I is: class B implements I {... } For example: The class Account can access the must provide an implementation of
36 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 35 ] Abstract Classes vs. Interfaces An abstract class can be used as a repository of A class can implement Both abstract classes and interfaces can be used to
37 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 36 ] Object-Oriented Design The design of a software system is an iterative process. choose develop previous step may indicate that develop etc. As the design matures, objects are abstracted into classes: group put determine Initial design effort focuses on the overall structure of the program. The algorithms for the methods are specified using pseudocode. Actual coding begins
38 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 37 ] Deciding on Objects and Classes Make some guesses about what the objects in the system are and try to arrange them into groups (which will be the classes). Although you should put serious thought into this, don t try to do this perfectly on the first pass. Rule of Thumb: Later you may need As you come up with the objects, some details (variables and methods) will be obvious. Document these and test them out with scenarios A scenario is a
39 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 38 ] Linked List Linked lists are useful when Linked lists are an example of Separate blocks of storage are Linked representations are an important alternative to Many key abstract data types (lists, stacks, queues, sets, trees, tables) can be represented with either Important to understand the
40 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 39 ] Pointers Pointers in Java are called However, you cannot
41 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 40 ] Linear Linked Lists The list consists of a series of Each node contains To realize this idea in Java: each class another class
42 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 41 ] Linear Linked Lists (cont d) Here is a diagram of the heap: Space complexity:
43 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 42 ] Linked List Example Node Class For a linked list of books, first define a class that represents individual list elements (nodes). The type of the link variable is the same as the class being defined
44 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 43 ] Linked List Example List Class Then define a class that represents
45 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 44 ] Linked List Operations What should be the operations on a linked list? Add some instance methods to the BookList class:
46 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 45 ] Using a Linked List Example:
47 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 46 ] Inserting at the Front of a Linked List Pseudocode: In Java (assuming the parameter is not null):
48 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 47 ] Inserting at the Front of a Linked List (cont d) What happens if we do step 1 and step 2 in the opposite order? Time Complexity:
49 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 48 ] Inserting at the End of a Linked List First, assume the list is empty (i.e., first equals null) Now, assume the list is not empty (i.e., first does not equal null) Howdowedostep1?
50 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 49 ] Inserting at the End of a Linked List (cont d) Time Complexity:
51 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 50 ] Using a Last Pointer To improve running time, keep a pointer to the last node in the list class, as well as the first node. Time Complexity:
52 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 51 ] Using a Last Pointer (cont d)
53 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 52 ] Deleting Last Node from Linked List Suppose we want to delete the node at the end of the list and return the deleted node. First, let s handle the boundary conditions: If the list is empty, If the list has only one element
54 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 53 ] Deleting Last Node from Linked List (cont d) Suppose the list has at least two elements. First attempt: Step 1 can be done as before. return this What about step 2?
55 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 54 ] Deleting Last Node from Linked List (cont d) Time Complexity: Would it help to keep a last pointer?
56 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 55 ] Linked Lists Pitfalls Check that a link is not null before following it! Example: Mark end of list Be careful with boundary cases! Draw memory diagrams! Don t lose access to needed objects!
57 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 56 ] Linked Lists vs. Arrays Space complexity: Time Complexity (n data items): insert front singly singly doubly doubly array linked linked, linked linked, last ptr last ptr insert end delete first delete last search
58 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 57 ] Linked Lists vs. Arrays (cont d) Suppose the items in the sequence are in sorted order. Then data items must be inserted in the correct place. But perhaps this will make searching for an item easier. Break the insertion process into two parts: 1. search 2. insert search singly singly doubly doubly array linked linked, linked linked, last ptr last ptr insert
59 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 58 ] Linked Lists vs. Arrays (cont d) Tradeoff: linked list: insert is search is because nodes arrays: insert is search is because nodes Binary search cannot be used on Later we will see some other data structures that try to
60 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 59 ] Other Linked Structures We don t have to restrict ourselves to just having one link instance variable per node. We can get arbitrarily complicated linked structures. Some of the more common and useful ones are: doubly linked list rings trees general graphs
61 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 60 ] Recursion Idea of recursion is closely related to the principle of Figure out how to Assume you have a Figure out how to This is also an application of Rules for recursive programs: There must be Recursive call(s) must
62 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 61 ] Stack Frames for Recursive Methods When a recursive method is executed, Example: The factorial of n, represented n!, is calculated as n èn, 1è èn, 2è 21. To compute n!:
63 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 62 ] Stack Frames for Factorial Example Stack frames when calling fact(4) :
64 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 63 ] Reversing a Linked List Recursively To find a recursive solution, break the problem down into a smaller problem. Let the list consist of nodes x 1 ;x 2 ;:::;x n. One idea: 1. Reverse 2. Put Step 1 solves a smaller problem; step 2 does a little more work to solve the larger problem. (A similar idea: 1. Reverse 2. Put Stopping case?
65 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 64 ] Reversing a Linked List Recursively (cont d) abstract class Node { Node link; } class LinkedList { Node first;... void reverselist() { first = reverse(first); } } reverselist is an instance method that Note a common occurrence:
66 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 65 ] Reversing a Linked List Recursively (cont d) reverse takes as a parameter reverse returns
67 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 66 ] Concatenating Two Lists Method concat appends the list starting with node b to the end of the list starting with node a. It returns a reference to the first node in the resulting list. Time Complexity: To reverse a list of n nodes takes
68 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 67 ] Figure for Reversing a Linked List Recursively
69 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 68 ] Reversing an Array Recursively Let A be an array of size n. To reverse A,wemust change which indexes are occupied by which data, so that at the end: A[0] contains A[1] contains etc. We can follow the ideas from the linked list: 1. save 2. recursively cause 3. store This breaks the problem of size n down into a subproblem of size n, 1. Stopping case:
70 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 69 ] Reversing an Array Recursively (cont d) The following reverses the elements of A starting at index start: The top level call is:
71 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 70 ] Figure for Reversing an Array Recursively
72 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 71 ] Towers of Hanoi Towers of Hanoi is is an example of a problem that is much easier to solve using recursion than not using recursion. There are 3 pegs and n disks, all of different sizes Initially all disks are on the start peg, stacked in decreasing size, with largest on bottom and smallest on top. We must move all the disks to the end peg The third peg Example: n =2. Solution is: 1. Move 2. Move 3. Move For larger n, it becomes difficult to figure out.
73 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 72 ] Recursive Solution to Towers of Hanoi Using recursion can help. Suppose someone gives us a method M to move n, 1 pegs. We can use it to solve the problem for n pegs as follows: 1. Move 2. Move 3. Move Steps 1 and 3 will be done Stopping case?
74 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 73 ] Figure for Towers of Hanoi
75 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 74 ] Recursive Solution to Towers of Hanoi (cont d) The output of the program will be a list of instructions. To call this method, suppose you have 4 pegs and you want to use peg 1 as the start peg, peg 3 as the finish peg, and peg 2 as the spare peg:
76 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 75 ] Time Complexity of Towers of Hanoi Solution Time Complexity: Asymptotically proportional to the number of Each instantiation of the method To count the number of instantiations, draw a Number of vertices in the tree is Therefore time complexity is
77 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 76 ] Parsing Arithmetic Expressions An important part of a compiler is the parser, which checks whether An important part of this problem is to check whether a +èb,èx=yèè a ++b=z èaèè c To simplify the problem: Assume that the operands are Only consider operators The correct syntax for arithmetic expressions can be described using
78 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 77 ] A Grammar for Arithmetic Expressions Sample Rules: (j means or ) Here are some derivations:
79 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 78 ] Recursive Parsing Algorithm Idea is to try to obtain an expression from the input. To do this, try to obtain from the input To obtain a term from the input (starting at the current position), try to obtain To obtain a factor from the input (starting at the current position), try to obtain
80 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 79 ] Recursive Parsing Algorithm (cont d) At the top level: boolean valid(string input) { String remainder = getexpr(input); return ((remainder!= null) && (remainder.length() == 0)); } getexpr recognizes an expression at the beginning of input and returns the rest of the string, which will be the empty string if nothing is left over. If a syntax error is encountered, it returns null. (Does not handle white space in the input.)
81 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 80 ] Recursive Parsing Algorithm (cont d)
82 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 81 ] Abstract Data Types An abstract data type (ADT) defines entities that have ADTs provide the benefits of There is a strict separation between This separation facilitates ADTs are easily achieved in
83 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 82 ] ADT Example: Priority Queue Specification The priority queue ADT is useful in many situations. Here is its specification: The state is The operations on a priority queue are: Note that there is no operation to Example applications: Pay Provide
84 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 83 ] Using a Priority Queue to Sort a List of Integers Even without knowing anything about how a priority queue might be implemented, we can take advantage of its operations to solve other problems. For example, to sort a list of numbers: Insert Successively Store
85 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 84 ] Implementing a Priority Queue with an Array
86 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 85 ] Implementing a Priority Queue with a Linked List Pseudocode: To insert an element: To remove the highest priority element: Scan When Time is Asymptotic running times are Time to sort is Can we do things faster by keeping the array, or linked list, elements in sorted order? Warning:
87 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 86 ] Implementing a PQ with a Sorted Array Keep the array elements in increasing order of priority. (If highest priority is smallest element, then elements will be in decreasing order). Pseudocode: To insert an element: To remove the highest priority element:
88 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 87 ] Implementing a PQ with a Sorted Linked List Pseudocode: To insert an element: To remove the highest priority element: Asymptotic times are
89 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 88 ] Generic PQ Implementation Using Java To avoid rewriting the priority queue implementation for every different kind of element (integer, double, String, user-defined classes, etc.), we can use Java s interface feature. All that is required is
90 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 89 ] Using the ComparisonKey Interface Change the specification of the PriorityQueue class to consist of a collection of Any class that Define a class called PQItem that sortpq, the sorting algorithm that uses a priority queue, can
91 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 90 ] Generic Implementation of PQ with Array class PriorityQueue { private ComparisonKey[] A = new ComparisonKey[100]; // int -> CK private int next; PriorityQueue() { next = 0; } public void insert(comparisonkey x) { // int -> CK A[next] = x; next++; } public ComparisonKey remove() { // int -> CK ComparisonKey high = A[0]; // int -> CK int highloc = 0; for (int cur = 1; cur < next; cur++) { if (high.compareto(a[cur]) == ComparisonKey.LOWER) { // use compareto method high = A[cur]; highloc = cur; } } A[highLoc] = A[next-1]; next--; return high; } }
92 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 91 ] Implementing the Generic PQItem Here is a possible PQItem class for integers. Note For a PQItem class for strings: make make the method
93 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 92 ] Generic PQItem s (cont d) This approach is particularly powerful since we can Suppose the items are One form of priority might be Another form might be All those decisions will be encapsulated inside the
94 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 93 ] Sorting with Generic PQ Finally, here is the sorting algorithm: void sortpq (ComparisonKey[] A) { int n = A.length; PriorityQueue pq = new PriorityQueue(); for (int i = 0; i < n; i++) pq.insert(a[i]); for (int i = 0; i < n; i++) A[i] = pq.remove(); } The only difference from before is IMPORTANT TO NOTICE: The PriorityQueue class The sortpq method
95 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 94 ] Importance of Modularity and Information Hiding Why is it valuable to be able to do these kinds of things? The public/private visibility modifiers of Java, and the discipline of not making the internal details be available outside are forms of Information hiding promotes modular programming you can The key to abstraction is
96 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name your program test. 1. edit 2. compile 3. if 4. run 5. if
97 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 96 ] Structure of a C Program A C program is a list of Every C program must contain Functions are The For The \n is Comments
98 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 97 ] A Useful Library See the Reek book (especially Chapter 16) for a description of what you can do with built-in libraries. In addition to stdio.h, stdlib.h lets you use functions for, e.g., math.h provides string.h has
99 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 98 ] Printf The function printf is used to print the standard output (screen): It can take a The first argument must The first argument might A Following the first argument is a Example: Output is:
100 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 99 ] Variables and Arithmetic Expressions The main numeric data types that we will use are: Variables are declared and manipulated in arithmetic expressions pretty much as in Java. For instance, However, in C,
101 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 100] Reading from the Keyboard The function scanf reads in data from the keyboard. scanf takes a The first argument is Each After the first argument is a The subsequent arguments must each be The code for an When you run this program, it will wait for you to enter two integers, and then continue. The integers can be on the same line separated by a space, or on two lines.
102 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 101] Functions Functions in C are pretty much like methods in Java (dealing only with primitive types). Example: #include < stdio.h > double times2 (double x) { x = 2*x; return x; } main () { double y = 301.4; printf("original value is %f; final value is %f.\n", y, times2(y)); } Functions must be As in Java, parameters are As in Java, if the function does not return any value, Parameters and local variables of functions
103 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 102] Recursive Functions Recursion is essentially the same as in Java. The only difference is if you have mutually recursive functions, also called indirect recursion: for instance, if function A calls function B, while B calls A. Then you have a problem with the requirement that functions be defined before they are used. You can get around this problem with
104 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 103] Global Variables and Constants C also provides global variables. A global variable is defined A global variable can be used Generally, global variables that can be changed are frowned upon, as contributing to errors. However, global variables are very appropriate for constants. Constants are defined using macros:
105 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 104] Boolean Expressions The operators to compare two values are the same as in Java: However, instead of returning a boolean value, they return Actually, C interprets Thus the analog in C of a boolean expression in Java is any expression that produces As in Java, boolean expressions can be operated on with Some examples: (10 == 3) evaluates to!(10 == 3) evaluates to!( (x < 4) (y == 5) ) :ifxis 10 and y is 5, then this evaluates to
106 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 105] If Statements and Loops Given the preceding interpretation of boolean expression, the following statements are the same in C as in Java: Since Boolean expressions are essentially integers, you can have a for statement like this in C: for (int count = 99; count; count--) {... } count is initialized to the loop is executed count is This loop is executed
107 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 106] Switch C has a switch statement that is like that in Java: switch ( <integer-expression> ) { case <integer-constant-1> : <statements-for-case-1> break; case <integer-constant-2> : <statements-for-case-2> break;... default : <default-statements> } Don t forget the break statements! The integer expression must produce a value belonging to any of the integral data types (various size integers and characters).
108 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 107] Enumerations This is something neat that Java does not have. An enumeration is a way to give For instance, suppose you need to have some codes in your program to indicate whether a library book is checked in, checked out, or lost. Intead of #define CHECKED_IN 0 #define CHECKED_OUT 1 #define LOST 2 you can use an enumeration declaration:
109 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 108] Using an Enumeration in a Switch Statement int status; /* some code to give status a value */ switch (status) { case CHECKED_IN : /* handle a checked in book */ break; case CHECKED_OUT : /* handle a checked out book */ break; case LOST : /* handle a lost book */ break; }
110 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 109] Enumeration Data Type You can give a name to an enumeration and thus create an enumeration data type. The syntax is: enum <name-of-enum-type> <actual enumeration> For example: enum book_status { CHECKED_IN, CHECKED_OUT, LOST }; Why bother to do this?
111 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 110] Type Synonyms The enumeration type is our first example of a user defined type in C. It s rather unpleasant to have to carry around the word enum all the time for this type. Instead, you can give a name to this type you have created, and subsequently just use that type without having to keep repeating enum. For example:
112 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 111] Structures C also gives you a way to create more general types of your own, as structures These are essentially like objects in Java, if you just consider the instance variables. A structure groups together related data items that can be of different types. The syntax to define a structure is:
113 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 112] Storage on the Stack The statement struct student stu; causes the entire stu structure to be stored
114 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 113] Using typedef with Structures When using the structure type, you have to carry along the word struct. To avoid this, you can use a A more concise way to do this is: Now you can create a Student variable:
115 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 114] Using a Structure You can access the pieces of a structure using dot notation (analogous to accessing instance variables of an object in Java) : You can also have the entire struct on either the left or the right side of the assignment operator:
116 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 115] Figure for Copying a Structure
117 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 116] Passing a Structure to a Function Structures can be passed as parameters to functions: Then you can call the function: But if you put the following line of code after the printf in print info:
118 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 117] Returning a Structure From a Function You can return a structure from a function also. Suppose you have the following function: Now you can call the function:
119 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 118] Figure for Returning a Structure from a Function The copying of formal parameters and return values can be avoided by
120 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 119] Arrays To define an array: For example: Unlike Java, Unlike Java, Unlike Java, As in Java, As in Java,
121 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 120] Arrays (cont d) Two things you CAN do: If you have an array of structures, You can declare a two-dimensional array (and higher): e.g., Two things you CANNOT do: We ll see how to accomplish these tasks
122 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 121] Pointers in C Pointers are used in C to circumvent copying of parameters and return values lasting changes access allow For each data type T, For instance, declares iptr to be of type pointer to int. iptr refers to a Actually, most C programmers write it as:
123 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 122] Addresses and Indirection Computer memory is Each variable is The address of the variable is iptr refers to *iptr refers to Applying the * operator is called
124 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 123] The Address-Of Operator We saw the & operator in scanf. It int i; int* iptr; i = 55; iptr = &i; *iptr = *iptr + 1; Last line gets data out of location whose address is in iptr, adds 1 to that data, and stores result back in location whose address is in iptr.
125 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 124] Comparing Indirection and Address-Of Operators As a rule of thumb: Indirection: It CANNOT It CAN Address-Of: It CAN It CANNOT
126 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 125] Pointers and Structures Remember the struct type Student, which has an int age and a double grade point: Student stu; Student* sptr; sptr = &stu; To access variables of the structure: There is a shorthand for this notation:
127 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 126] Passing Pointer Variables as Parameters You can pass pointer variables as parameters. void printage(student* sp) { printf("age is %i",sp->age); } When this function is called, 1. a Student* variable: or 2. apply the & operator to a Student variable: C still uses call by value to pass pointer parameters, but because they are pointers, what gets copied are Data coming in to the function is not copied.
128 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 127] Passing Pointer Variables as Parameters (cont d) Now we can void changeage(student* sp, int newage) { sp->age = newage; } You can also Old initialize with copying: Student initialize(int old, double gpa) { Student st; st.age = old; st.grade_point = gpa; return st; } More efficient initialize using pointers:
129 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 128] Passing Pointer Variables as Parameters (cont d) Using pointers is an optimization in previous case. But it is void swapages (Student* sp1, Student* sp2) { int temp; temp = sp1->age; sp1->age = sp2->age; sp2->age = temp; } To call this function:
130 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 129] Pointers and Arrays The name of an array is It is a To reference array elements, you can use or What is going on with the pointer notation? a refers to *a refers to a+1 refers to *(a+1) refers to
131 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 130] Pointers and Arrays (cont d) You can also refer to array elements with For example, int a[5]; int* p; p = a; /* p = &a[0]; is same */ p refers to *p refers to p+1 refers to *(p+1) refers to Since p is a non-constant pointer, you can also Warning: NO BOUNDS CHECKING IS DONE IN C!
132 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 131] Passing an Array as a Parameter To pass an array to a function: void printallages(int a[], int n) { int i; for (i = 0; i < n; i++) { printf("%i \n", a[i]); } } The array parameter indicates Alternative definition: void printallages(int* p, int n) { int i; for (i = 0; i < n; i++) { printf("%i \n", *p); p++; } } The formal array parameter is a You can call the function like this:
133 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 132] Dynamic Memory Allocation in Java Java That means that This happens whenever In Java there is strict distinction between Every variable is either memory for variables is This memory memory for variables of primitive type memory that holds the actual contents of an object is This memory goes away
134 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 133] Dynamic Memory Allocation in C In C, Every type has the possibility of being allocated statically (on the stack) or dynamically (on the heap). To allocate space statically, you Space is allocated To allocate space dynamically, use It takes one integer parameter indicating the Use sizeof operator to get the length; It returns a The pointer has type void*. You MUST cast it to the appropriate type. If malloc fails to allocate the space,
135 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 134] malloc Example To dynamically allocate space for an int: int* p; p = (int*) malloc(sizeof(int)); /* cast result to int* */ if (p == NULL) { /* to be on the safe side */ printf("malloc failed!"); } else { *p = 33; printf("%i", *p); } Normally, you don t need to allocate a single integer at a time. Typically, you would use malloc to: allocate allocate
136 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 135] Another malloc Example To dynamically allocate space for a structure: Student* sptr; sptr = (Student*) malloc(sizeof(student)); sptr->age = 20; sptr->grade_point = 3.4;
137 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 136] Allocating a Linked List Node Dynamically For a singly linked list of students, use this type: typedef struct Stu_Node{ int age; double grade_point; struct Stu_Node* link; } StuNode; To allocate a node for the list: To insert the node pointed to by sptr after the node pointed to by some other node, say cur:
138 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 137] Allocating an Array Dynamically To allocate an array dynamically, int i; int* p; p = (int*) malloc(100*sizeof(int)); /* 100 elt array */ /* now p points to the beginning of the array */ for (i = 0; i < 100; i++) /* initialize the array */ p[i] = 0; /* access the elements */ Similarly, you can allocate an array of structures:
139 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 138] Deallocating Memory Dynamically When memory is allocated using malloc, You can get void sub() { int *p; p = (int*) malloc(100*sizeof(int)); return; } Although the space for the pointer variable p goes away when sub finishes executing, But they are completely useless after sub is done, If you had wanted them to be accessible outside of sub,
140 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 139] Using free To deallocate memory when you are through with it, It takes as an argument a and returns nothing. The result of free is that all the space starting at the designated location will be In the function void sub above, just before the return, you should say: DO NOT DO THE FOLLOWING:
141 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 140] Saving Space with Arrays of Pointers Suppose you need an array of structures, where each structure is fairly large. But you are not sure at compile time how big the array needs to be. 1. Allocate 2. Find out 3. Allocate
142 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 141] Array of Pointers Example To implement with the usual Student struct:
143 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 142] Information Hiding in C Java provides support for information hiding by Advantages of data abstraction, including the use of constructor and accessor (set and get) functions: push easier easy easy C does not provide the same level of compiler support as Java, but you can achieve the same effect with some
144 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 143] Information Hiding in C (cont d) A constructor in C would be a function that calls initializes returns For example:
145 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 144] Information Hiding in C (cont d) The analog of a Java instance method in C would be a function whose first parameter is the object to be operated on. You can write set and get functions in C:
146 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 145] Information Hiding in C (cont d) You can use the set and get functions to swap the ages for two student objects: When should you provide set and get functions and when should you not? They obviously impose some overhead in terms of additional function calls.
147 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 146] Strings in C There is no explicit string type in C. A string in C is an array of characters that is terminated with the null character. The length The null character A sequence of characters enclosed in double quotes
148 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 147] Strings in C (cont d) You can also declare a To initialize name, do not assign to a string literal! Instead, either Access elements using the brackets notation: char firstletter; name[3] = a ; firstletter = name[0]; nameptr[3] = b ; firstletter = nameptr[0];
149 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 148] Passing Strings to and from Funtions To pass a string into a function or return one from a function, you must Passing in a string: Returning a string: You can call these functions like this:
150 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 149] Reading in a String from the User To read in a string from the user, call: scanf("%s", name); Notice the use of %s in scanf. The corresponding data must be a scanf reads a string from the input stream up to The letters are read into You must make sure that you have a large enough array to hold the string. How much space is needed? If you don t have enough space, whatever follows the array will be
151 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 150] String Manipulation Functions There are some useful string manipulation functions provided for you in C. These include: strlen, which takes a string as an argument and returns the length of the string, not counting the null character at the end. I.e., it counts how many characters it encounters before reaching \0. strcpy, which takes two strings as arguments and copies its second argument to its first argument. First, to use them, you need to include headers for the string handling library: #include <string.h> To demonstrate the use of strlen and strcpy, suppose you want to add a name component to the Student structure and change the constructor so that it asks the user interactively for the name:
152 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 151] String Manipulation Functions Example typedef struct { char* name; int age; double grade_point; } Student; Student* constructstudent(int age, double gpa) { char inputbuffer[100]; /* read name into this */ Student* sptr; sptr = (Student*) malloc(sizeof(student)); sptr->age = age; sptr->grade_point = gpa; /* here s the new part: */ printf("enter student s name: "); scanf("%s", inputbuffer); /* allocate just enough space for the name */ sptr->name = (char*) malloc ( (strlen (inputbuffer) + 1)*sizeof(char) ); /* copy name into new space */ strcpy (sptr->name, inputbuffer); return sptr; } When constructor returns, inputbuffer goes away. Space allocated for Student object is an int,a double and just enough space for the actual name.
153 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 152] Other Kinds of Character Arrays Not every character array has to be used to represent a string. You may want a character array that holds all possible letter grades, for instance: char grades[5]; grades[0] = A ; grades[1] = B ; grades[2] = C ; grades[3] = D ; grades[4] = F ; In this case, there is no reason for the last array entry to be the null character, and in fact, it is not.
154 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 153] File Input and Output File I/O is much simpler than in Java. Include Declare Call Writing to a file is done with Reading from a file is done with Call
155 CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 154] File I/O Example /* to use the built in file functions */ #include <stdio.h> main () { /* create a pointer to a struct called FILE; */ /* it is system dependent */ FILE* fp; char line[80]; int i; /* open the file for writing */ fp = fopen("testfile", "w"); /* write into the file */ fprintf(fp,"line %i ends \n", 1); fprintf(fp,"line %i ends \n", 2); /* close the file */ fclose(fp); /* open the file for reading */ fp = fopen("testfile", "r"); /* read six strings from the file */ for (i = 1; i < 7; i++) { fscanf(fp,"%s", line); printf("got from the file: %s \n", line); } /* close the file fclose(fp); }
Compiling and Running a C Program in Unix
CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 95 ] Compiling and Running a C Program in Unix Simple scenario in which your program is in a single file: Suppose you want to name
More informationRules for Abstract Classes and Methods
CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 32 ] Rules for Abstract Classes and Methods æ Only instance methods can be declared abstract (not static methods). æ Any class with
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationKurt Schmidt. October 30, 2018
to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationObject Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.
CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java
More informationChapter 1: Object-Oriented Programming Using C++
Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms
More informationMARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012
MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)
More informationProcedural programming with C
Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical
More informationAryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9
Fundamental of C Programming Unit I: Q1. What will be the value of the following expression? (2017) A + 9 Q2. Write down the C statement to calculate percentage where three subjects English, hindi, maths
More informationadvanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef
today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationA Fast Review of C Essentials Part I
A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types
More informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More informationPace University. Fundamental Concepts of CS121 1
Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction
More informationCE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings
CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location
More informationCSE351 Winter 2016, Final Examination March 16, 2016
CSE351 Winter 2016, Final Examination March 16, 2016 Please do not turn the page until 2:30. Rules: The exam is closed-book, closed-note, etc. Please stop promptly at 4:20. There are 125 (not 100) points,
More informationMODULE 5: Pointers, Preprocessor Directives and Data Structures
MODULE 5: Pointers, Preprocessor Directives and Data Structures 1. What is pointer? Explain with an example program. Solution: Pointer is a variable which contains the address of another variable. Two
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationData Structure. Recitation III
Data Structure Recitation III Topic Binary Search Abstract Data types Java Interface Linked List Binary search Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions.
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationJTSK Programming in C II C-Lab II. Lecture 3 & 4
JTSK-320112 Programming in C II C-Lab II Lecture 3 & 4 Xu (Owen) He Spring 2018 Slides modified from Dr. Kinga Lipskoch Planned Syllabus The C Preprocessor Bit Operations Pointers and Arrays (Dynamically
More informationPointers in C/C++ 1 Memory Addresses 2
Pointers in C/C++ Contents 1 Memory Addresses 2 2 Pointers and Indirection 3 2.1 The & and * Operators.............................................. 4 2.2 A Comment on Types - Muy Importante!...................................
More informationComputers Programming Course 5. Iulian Năstac
Computers Programming Course 5 Iulian Năstac Recap from previous course Classification of the programming languages High level (Ada, Pascal, Fortran, etc.) programming languages with strong abstraction
More informationPreface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS
Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review
ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27 Midterm #2 Review 1 Time and Location The midterm will be given in class during normal class hours, 11:00a.m.-12:15p.m.,
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationInstantiation of Template class
Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double
More informationDEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS 1. Define global declaration? The variables that are used in more
More informationCPSC 211, Sections : Data Structures and Implementations, Honors Final Exam May 4, 2001
CPSC 211, Sections 201 203: Data Structures and Implementations, Honors Final Exam May 4, 2001 Name: Section: Instructions: 1. This is a closed book exam. Do not use any notes or books. Do not confer with
More informationFile Input and Output
CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 153] File Input and Output File I/O is much simpler than in Java. æ Include stdio.h to use built-in file functions and types æ Declare
More informationZhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson
Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program
More informationMotivation was to facilitate development of systems software, especially OS development.
A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.
More informationCourse Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++
Introduction to Programming in C++ Course Text Programming in C++, Zyante, Fall 2013 edition. Course book provided along with the course. Course Description This course introduces programming in C++ and
More informationWriting an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and
Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and #include The Use of printf() and scanf() The Use of printf()
More informationWhat are the characteristics of Object Oriented programming language?
What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is
More informationCpt S 122 Data Structures. Course Review Midterm Exam # 2
Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm
More informationSEMANTIC ANALYSIS TYPES AND DECLARATIONS
SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether
More informationAnatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?
Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator
More informationB.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University
Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are
More information211: Computer Architecture Summer 2016
211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Structure: - header files - global / local variables - main() - macro Basic Units: - basic data types - arithmetic / logical / bit operators
More informationReview Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:
More informationLecture 05 I/O statements Printf, Scanf Simple statements, Compound statements
Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple
More informationReview sheet for Final Exam (List of objectives for this course)
Review sheet for Final Exam (List of objectives for this course) Please be sure to see other review sheets for this semester Please be sure to review tests from this semester Week 1 Introduction Chapter
More informationDEEPIKA KAMBOJ UNIT 2. What is Stack?
What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you
More informationMotivation was to facilitate development of systems software, especially OS development.
A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.
More informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee
ECE 250 / CS 250 Computer Architecture C to Binary: Memory & Data Representations Benjamin Lee Slides based on those from Alvin Lebeck, Daniel Sorin, Andrew Hilton, Amir Roth, Gershon Kedem Administrivia
More informationLesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014
Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class
More informationCpt S 122 Data Structures. Data Structures
Cpt S 122 Data Structures Data Structures Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Introduction Self Referential Structures Dynamic Memory Allocation
More informationIntroduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.
Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and
More informationCS 445: Data Structures Final Examination: Study Guide
CS 445: Data Structures Final Examination: Study Guide Java prerequisites Classes, objects, and references Access modifiers Arguments and parameters Garbage collection Self-test questions: Appendix C Designing
More informationExam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming
Exam 1 Prep Dr. Demetrios Glinos University of Central Florida COP3330 Object Oriented Programming Progress Exam 1 is a Timed Webcourses Quiz You can find it from the "Assignments" link on Webcourses choose
More informationIMPORTANT QUESTIONS IN C FOR THE INTERVIEW
IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.
More informationTOPIC 2 INTRODUCTION TO JAVA AND DR JAVA
1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared
More informationCPS 506 Comparative Programming Languages. Programming Language
CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support
More informationReviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand
More information+ Abstract Data Types
Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract
More informationCS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output
CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables
More informationFor instance, we can declare an array of five ints like this: int numbers[5];
CIT 593 Intro to Computer Systems Lecture #17 (11/13/12) Arrays An array is a collection of values. In C, as in many other languages: all elements of the array must be of the same type the number of elements
More informationLinear Data Structure
Linear Data Structure Definition A data structure is said to be linear if its elements form a sequence or a linear list. Examples: Array Linked List Stacks Queues Operations on linear Data Structures Traversal
More informationBLM2031 Structured Programming. Zeyneb KURT
BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help
More informationPostfix (and prefix) notation
Postfix (and prefix) notation Also called reverse Polish reversed form of notation devised by mathematician named Jan Łukasiewicz (so really lü-kä-sha-vech notation) Infix notation is: operand operator
More informationProgramming for Engineers Arrays
Programming for Engineers Arrays ICEN 200 Spring 2018 Prof. Dola Saha 1 Array Ø Arrays are data structures consisting of related data items of the same type. Ø A group of contiguous memory locations that
More information1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8
Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(
More informationChapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language
Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented
More informationCS113: Lecture 4. Topics: Functions. Function Activation Records
CS113: Lecture 4 Topics: Functions Function Activation Records 1 Why functions? Functions add no expressive power to the C language in a formal sense. Why have them? Breaking tasks into smaller ones make
More informationTopics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)
Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types
More informationDefining Classes and Methods
Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.
More informationMultiple choice questions. Answer on Scantron Form. 4 points each (100 points) Which is NOT a reasonable conclusion to this sentence:
Multiple choice questions Answer on Scantron Form 4 points each (100 points) 1. Which is NOT a reasonable conclusion to this sentence: Multiple constructors for a class... A. are distinguished by the number
More informationFORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE
TED (10)-3071 Reg. No.. (REVISION-2010) Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE (Common to CT and IF) [Time: 3 hours (Maximum marks: 100)
More informationComputer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary
GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis
More informationProblem Solving with C++
GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter
More informationC: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36
Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar
More informationChapter 4 Defining Classes I
Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the
More informationCS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018
CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make
More informationPRINCIPLES OF OPERATING SYSTEMS
PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)
More informationLinked Data Representations. Data Structures and Programming Techniques
Linked Data Representations 1 Linked Data Representations Linked data representations such as lists, stacks, queues, sets and trees are very useful in Computer Science and applications. E.g., in Databases,
More informationCONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17
List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code
More informationData Structures and Algorithms for Engineers
04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University
More informationC & Data Structures syllabus
syllabus Overview: C language which is considered the mother of all languages, is and will be the most sought after programming language for any beginner to jump start his career in software development.
More information6.001 Notes: Section 8.1
6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything
More informationLargest Online Community of VU Students
WWW.VUPages.com http://forum.vupages.com WWW.VUTUBE.EDU.PK Largest Online Community of VU Students MIDTERM EXAMINATION SEMESTER FALL 2003 CS301-DATA STRUCTURE Total Marks:86 Duration: 60min Instructions
More informationCollege Board. AP CS A Labs Magpie, Elevens, and Picture Lab. New York: College Entrance Examination Board, 2013.
AP Computer Science August 2014 June 2015 Class Description AP Computer Science is the second class after Pre-AP Computer Science that together teach the fundamentals of object-oriented programming and
More informationAbout this exam review
Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,
More informationChapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures
Chapter 5: Procedural abstraction Proper procedures and function procedures Abstraction in programming enables distinction: What a program unit does How a program unit works This enables separation of
More informationLecture Topics. Administrivia
ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality
More informationUnderstanding Pointers
Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer
More informationPointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory
Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have
More informationOBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe
OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++
More informationData Structure Series
Data Structure Series This series is actually something I started back when I was part of the Sweet.Oblivion staff, but then some things happened and I was no longer able to complete it. So now, after
More informationChapter 3 Syntax, Errors, and Debugging. Fundamentals of Java
Chapter 3 Syntax, Errors, and Debugging Objectives Construct and use numeric and string literals. Name and use variables and constants. Create arithmetic expressions. Understand the precedence of different
More informationESC101N: Fundamentals of Computing End-sem st semester
ESC101N: Fundamentals of Computing End-sem 2010-11 1st semester Instructor: Arnab Bhattacharya 8:00-11:00am, 15th November, 2010 Instructions 1. Please write your name, roll number and section below. 2.
More information