Dynamic Memory Allocation using a Custom Implemented Single-Linked List

Size: px
Start display at page:

Download "Dynamic Memory Allocation using a Custom Implemented Single-Linked List"

Transcription

1 Dynamic Memory Allocation using a Custom Implemented Single-Linked List Anders Eiler April 8, Introduction The objective of this paper is to describe how to dynamically allocate memory at runtime and store any given data type in a custom implementation of a Single-Linked List in the C++ programming language. I will start by talking briefly about the fundamentals of memory allocation, dynamic memory allocation, pointers, iterators, templates and operator overloading to give an understanding of the elements behind the final implementation of the Single-Linked List. Following this is a description of my implementation of a Single-Linked List. Finally, I will compare my findings with experience from PHP, a scripting language that is probably the most opposite to C++ one can find. But first, let us start with some thoughts on memory allocation in general and why this is an interesting topic. Memory allocation Usually, the size of an array has to be declared at compile time, meaning it has to be defined in the source code. 1 int ary [3]; // gives us an array named ary with 3 slots to contain ints This can lead to a number of potential issues: It can be difficult to conditionally declare a variable. The size of any array must be determined at compile-time. As an example, trying to use the same approach as in the previous Listing to dynamically set the size of an array during runtime would fail: 1

2 1 std :: cout << " Type in the size of your array : "; 2 int arysize ; 3 cin >> arysize ; 4 5 int ary [ arysize ]; // this fails, as the size of an array must be constant! Any C++ programmer needs to be aware of the memory usage of his program. The fact that we can t dynamically set the size of an array or resize it dynamically during runtime is often inappropriate, as we may not know the actual size of an array at compile-time. Consider a case where we want to save the zip-code of anybody shopping at a grocery store for one day in C++. We do not know in advance how many shoppers there will be. One solution could be to make the array so big, that we know there is enough space: 1 int shopperszipcodes [10000]; That, however, is also inconvenient for a number of reasons: If there are any less than shoppers that day, it will be a waste of memory to allocate enough space in the array for If there are more than shoppers in one day, it can lead to either an artificial buffer where any shopper after no is not saved, or it may lead to buffer overflow which will cause the program to crash. The answer to this question is usage of dynamic memory allocation which, in C++, is natively implemented using the new and delete. I will be using these in my implementation of the Single-Linked list (which I ll get back to later), but first, let us take a look at the basics of pointers, Dynamic memory allocation, iterators, templates and operator overloading. 2 Pointers When you want to save some value in some variable, it is stored in the memory, and the variable you have at hand points to the value that you have assigned to it in the memory. As soon as a variable is declared, the appropriate amount of space (depending on the type) is allocated in the memory. All memory cells has an address. The actual addresses are different from system to system, but let us assume our address cells are named from 1000 and on forth. To get the address of the memory cell that the value of a variable is stored in, the & (ampersand) operator is used. 2

3 1 int firstvar = 10; // a regular declration of a variable that is assigned the value. 2 cout << " The address of firstvar is: " << & firstvar ; // gets the address in the memory. In our case, it returns "1000". In the same way that & (ampersand) gets the address in the memory, the * dereferences a pointer. A pointer always contains the address in the memory of the variable it is pointing to. If you want the content of that memory cell, the pointer has to be dereferenced using the *. The * is also used when declaring a new pointer. It is the same sign used in two different contexts. It is shown in the following example: 1 # include <iostream > 2 using namespace std ; 3 4 int main () { 5 int valone, valtwo ; 6 int * ptr ; 7 8 ptr = & valone ; // assign the address of valone to the pointer. 9 * ptr = 10; // set the value of the memory cell that the pointer is pointing to = ptr = & valtwo ; // now set the pointer to point to the address of valtwo 11 * ptr = 20; // same as before, set the value to cout << " The value of valone = " << valone << "\ n"; // prints cout << " The value of valtwo = " << valtwo << "\ n"; // prints return 0; 17 } Pointers can be manipulated using Pointer arithmetics. If you have a pointer p1 that points to the address 1010, then p1+1 would make the pointer point to address This allows us to iterate tough an array using pointers. Pointers can also be parsed as arguments to functions. This is very powerful, compared to parsing variables by value, which would parse a copy of the value to the function. In that case, the value will be limited to the scope of the function. When a pointer is parsed instead, the function is able to modify the value of the pointer in the global scope. Now we have the basics of memory allocation and pointers in place. accelerate and look at Dynamic Memory Allocation! Let us 3

4 3 Dynamic Memory Allocation In the case that we need dynamic memory allocation, we need to use the new operator: 1 // generic notation : 2 // pointer = new type ; 3 // pointer = new type [ number_of_elements ]; 4 5 int * ptr ; // create a new pointer. 6 ptr = new int ; // allocate memory for an integer and point ptr to the address of that integer. 7 * ptr = 10; The new operator always returns the address of the object it has allocated. Any dynamically allocated memory is placed in the heap of the system. The address that is returned can be saved in a pointer, which can later be used to dereference the pointer to gain access to the actual value. In C++, one must free any memory that has been dynamically allocated. This is done using the delete operator. 1 delete ptr ; The procedure is almost the same when dynamically allocating arrays compared to dynamically allocating single variables: 1 int arysize = 20; 2 int * aryptr = new int [ arysize ]; 3 aryptr [15] = 1; 4 delete [] aryptr ; The main differences is that, when working with arrays, the delete[] must be used to free the memory. Once the array is initiated, it can be handled like any other array in C++. I will use dynamic memory allocation to assign new nodes to my Single-Linked List [SLL], which is what enables the dynamic addition of new nodes at runtime (and thereby dynamic memory allocation) in the SLL. 4 Operator Overloading, Iterators & Templates This section will briefly cover each of the three topics, as these are also some of the building blocks of my custom SLL implementation. 4

5 Operator Overloading From regular mathematics we are used to working with operators such as (+), (-), (=) etc. We also know how to use these in programming languages, comparing using (==) etc. The concept of Operator Overloading allows an operator to be extended to work with not just the built-in types, but also custom types and classes. In my SLL I need to compare node elements, increment iterators etc. To make this as easy as possible, operator overloading is used with the iterator class. 1 iterator operator ++( int ) { 2 iterator itr_old = * this ; 3 ++(* this ); 4 return itr_old ; 5 } The Listing above is a snippet from the SLL implementation. It shows an operator overloading of the (++) operator. It is used to increment an iterator (covered in the Section 4). As iterators in my SLL are pointers to nodes, the regular (++) operator, which per default is build to work on incrementing integers, would fail. The operator overloading states that, whenever the (++) operator is used on an object of the iterator class, it means what is defined on line 2-4, namely to increment a pointer (which we saw in Section 2 is possible) and return the updated iterator. Iterators An iterator is an object that has the ability to iterate through a range of elements. It will point to an element in the range, and using a defined set of operators such as (++), (- -) and (*) (dereference), it can iterate through the range. Such a range can be a list, an array or similar. An iterator is often implemented as a pointer that is pointing to an element in e.g. an array. It can iterate through the array using (++) to increment the pointer. Iterators are fundamental to the implementation of my SLL for two reasons: 1) it allows the client program to iterate through the list without having to deal with the internals of its implementation and 2) by following the standard of iterators, it allows the client program to switch between my SLL and other container libraries. The following Listing shows the implementation of an iterator in my SLL. It is based on the base class of an iterator and extends the default iterator class. 1 class iterator : public std :: iterator < std :: forward_iterator_tag, T, size_t, T*, T& > { 2 5

6 3 public : 4 Node * list_curpos ; // an internal pointer to the current position in the list 5 typedef T* pointer ; 6 typedef T& reference ; 7 iterator ( Node * cur_node = NULL ) : list_curpos ( cur_node ) {} 8 9 // some operator overloading that allows us to work with the linked list 10 reference operator *() { return list_curpos - > value ; } 11 pointer operator - >() { return &(** this ); } 12 iterator & operator ++() { list_curpos = list_curpos - > next ; return * this ; } // prefix incremental ( no argument ) 13 iterator operator ++( int ) { iterator itr_old = * this ; ++(* this ); return itr_old ; } // postfix incremental ( hence the int argument ) 14 bool operator ==( iterator const & emt ) { return list_curpos == emt. list_curpos ; } 15 bool operator!=( iterator const & emt ) { return!(* this == emt ); } 16 }; Templates C++ is a type-strong programming language. My SLL should be designed such that its nodes can contain elements of any given value type, as long as all elements in a list is of the same type. Instead of defining the functions of the SLL with a specific type, they are defined as Function Templates a special function that can operate on generic types. This means that a Function Template can be used on more than one type or class without having to repeat the entire function code for each data type that it is supposed to work with. 1 template < typename T> 2 class LinkedList { 3 4 private : 5 struct Node { 6 Node (T val ) : next ( NULL ), value ( val ) {} 7 Node * next ; 8 T value ; 9 }; public : 12 void push_front ( T const & element ); 13 void push_back ( T const & element ); 14 void insert_after ( iterator itr, T const & element ); 15 }; The Listing above shows a snippet of the class definition of my LinkedList class which is the basis of the SLL. Line 1 tells that the typename will be identified T in the class. Line 5-9 defines the nodes that the SLL is made up of. Its values are of the type <T>, meaning it can be whatever is chosen upon initialization of 6

7 the SLL. The same goes for the three methods on line 12-15, where the datatype <T> is used. 1 LinkedList <int > mylist ; The Listing above shows how to initialize a SLL containing integers. Any data type can be used here - build in ones or custom made ones, which is the case in my implementation. Now that all the basics are in place, let us look at the actual Single-Linked List. 5 Implementation of a Single Linked List C++ comes with a build-in type std::list, which is a double-linked list. This SLL implementation is mostly a proof of concept, showing how a SLL that can take any type object can be implemented. In most cases, a double-linked list is preferable as it is faster to traverse and update. However, in some cases it can be efficient to use a SLL over a double-linked list. A SLL uses less memory as it only has one pointer per node (to the next element in the list), and under certain circumstances it can be preferred. The SLL consists of Node objects. Each node object has a value of type <T> and a pointer to the next node in the list. The value contains an object of the type that is defined upon initialization of the list. The SLL is implemented using Function Templates to ensure that it can contain any type of objects. Iterators are implemented to hide the internal functionality of the list, and only present the client program with the iterator for navigation and manipulation of the list. Operator Overloading is used to enable the list to manipulate the iterators. Here I will present selected code snippets of the SLL. The parts regarding operator overloading, iterators and templates was presented in Section 4. The rest of the code follows the same idea by using the Template <typename T>, changing only the body of each function. These can be seen in the attached files. 1 template < typename T> 2 typename LinkedList <T >:: iterator LinkedList <T >:: begin () { 3 return iterator ( list_head ); 4 } This first Listing shows the begin() method that returns an iterator pointing to the head of the list. This is very useful in several cases, e.g. when traversing the list. It once again shows how a template is used to use the type T (the generic type). It returns an iterator which is constructed, and points to list_head, a pointer that always points to the node in the head of the list. 1 template < typename T> 2 void LinkedList <T >:: push_front ( T const & element ) { 7

8 3 Node * newnode = new Node ( element ); 4 newnode - > next = list_head ; 5 list_head = newnode ; 6 7 if( list_tail == NULL ) { 8 list_tail = newnode ; 9 } list_size ++; 12 } This next Listing shows the push_front() method. It takes an element (once again of type T) and inserts it at the head of the list. A new node is created on line 3, and the head of the list is set to point to this node. The next pointer of this node is set to point to the old head, and this new node is thereby inserted as the head of the list. 1 dataelement * e1 = new dataelement ; 2 e1 -> name = " Element #1"; 3 e1 - > phone = 1111; 4 5 // (...) 6 7 dataelement * e5 = new dataelement ; 8 e5 -> name = " Element #5"; 9 e5 - > phone = 5555; LinkedList < dataelement > elst ; 12 LinkedList < dataelement >:: iterator eit ; 13 elst. push_front (* e1); 14 elst. push_back (* e2); 15 elst. push_back (* e3); eit = elst. begin (); eit ++; 18 elst. insert_after (eit, *e4); 19 elst. push_back (* e5); for ( eit = elst. begin (); eit!= NULL ; ++ eit ) { 22 std :: cout << eit -> name << " - " << eit -> phone << "\n"; 23 } // Output : 26 // Element # // Element # // Element # // Element # // Element # This final Listing shows a part of the client-program that comes with the SLL. It creates 5 objects of the type dataelement, which is a type defined as a struct to be the value of the nodes. The 5 dataelement objects are added to the list using different methods, some are then removed and it is finally printed. 8

9 This client program is static, but another client program that takes user input is able to add new nodes to the SLL in the same way, and thereby dynamically assigning memory at runtime. 6 Comparison with Other Programming Languages - PHP My background is based on various scripting languages such as PHP and Python. The steps in going from such a scripting language to a programming language like C++ are enormous. Amongst the most noticeable things that I have found are: Pointers: References etc. does exists in PHP, but is not used nearly as much as in C++. Having to wrap your mind around using pointers for everything is a new but very powerful concept, compared to e.g. PHP scripting. Object types & Templates: PHP is type coerced, meaning that it doesn t really care if a variable contains an int, string or double. Having to determine the type of everything at the time it is initiated forces you to think further, which I personally see as a good thing. Operator overloading: This does not exists in PHP, and is therefore a completely new concept when coming from such a background. However, looking at C++ as a whole, the fact that it is type safe etc., means that operator overloading is very useful, and it is used a lot in the implementation of my SLL. Memory management: This concept doesn t really exists in PHP either. Of course you can make a script that consumes all available memory, but having to think about memory management, garbage collecting in regular programming is a new - but also good - aspect of writing software. The four bullets above are just some of the things I noticed the most when I had to switch from a scripting language to doing advanced programming in C++. It is possible to implement a SLL in PHP, but the way you must think when programming (not scripting!) in C++ is - in my eyes - a much better approach to software engineering, as it forces you to consider and think about more deep aspects of how you want your program to work. 9

10 The following references have been used as inspiration for the theory, examples and thoughts on the topics of memory allocation, pointers, iterators, templates, operator overloading and linked lists: References [1] Alex. Dynamic memory allocation with new and delete, URL: 69-dynamic-memory-allocation-with-new-and-delete/. [2] David Bolton. C++ tutorial - advanced pointers, URL: cplus.about.com/od/learning1/ss/pointers2.htm. [3] computerquip cplusplus.com. Linked lists, URL: cplusplus.com/articles/lw6ac542/. [4] cplusplus.com. Dynamic memory. URL: doc/tutorial/dynamic/. [5] cplusplus.com. Lists. URL: list/list/. [6] cplusplus.com. Pointers. URL: tutorial/pointers/. [7] cplusplus.com. Templates. URL: tutorial/templates/. [8] Nasif M. How to create linked list using c/c++, URL: How-to-create-Linked-list-using-C-C. [9] Bjarne Stroustrup. The C++ Programming Language - Iterators, p [10] Bjarne Stroustrup. The C++ Programming Language - Operator Overloading, p [11] Bjarne Stroustrup. The C++ Programming Language - Pointers, Arrays, and Structures, p [12] Bjarne Stroustrup. The C++ Programming Language - Templates, p [13] Varun Sud. Pointers usage in c++: Beginners to advanced, URL: Pointers-Usage-in-C-Beginners-to-Advanced#c. 10

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists Lecture 11 Doubly Linked Lists & Array of Linked Lists In this lecture Doubly linked lists Array of Linked Lists Creating an Array of Linked Lists Representing a Sparse Matrix Defining a Node for a Sparse

More information

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer. Coding Rules Section A: Linux kernel style based coding for C programs Coding style for C is based on Linux Kernel coding style. The following excerpts in this section are mostly taken as is from articles

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure Short Notes on Dynamic Memory Allocation, Pointer and Data Structure 1 Dynamic Memory Allocation in C/C++ Motivation /* a[100] vs. *b or *c */ Func(int array_size) double k, a[100], *b, *c; b = (double

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum

Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum Integrating the C++ Standard Template Library Into the Undergraduate Computer Science Curriculum James P. Kelsh James.Kelsh@cmich.edu Roger Y. Lee lee@cps.cmich.edu Department of Computer Science Central

More information

Common Data Structures

Common Data Structures Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E. Chapter 5 Linked Lists Data Structures Using C++ 2E Chapter 5 Linked Lists Test #1 Next Thursday During Class Cover through (near?) end of Chapter 5 Objectives Learn about linked lists Become aware of the basic properties of

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 25, 2015 Outline Outline 1 Chapter 12: C++ Templates Outline Chapter 12: C++ Templates 1 Chapter 12: C++ Templates

More information

C++ Language Tutorial

C++ Language Tutorial cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain

More information

DATA STRUCTURES USING C

DATA STRUCTURES USING C DATA STRUCTURES USING C QUESTION BANK UNIT I 1. Define data. 2. Define Entity. 3. Define information. 4. Define Array. 5. Define data structure. 6. Give any two applications of data structures. 7. Give

More information

Tutorial on C Language Programming

Tutorial on C Language Programming Tutorial on C Language Programming Teodor Rus rus@cs.uiowa.edu The University of Iowa, Department of Computer Science Introduction to System Software p.1/64 Tutorial on C programming C program structure:

More information

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators This handout is designed to provide a better understanding of how one should write template code and architect iterators

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

10CS35: Data Structures Using C

10CS35: Data Structures Using C CS35: Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C OBJECTIVE: Learn : Usage of structures, unions - a conventional tool for handling a

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6) Semantic Analysis Scoping (Readings 7.1,7.4,7.6) Static Dynamic Parameter passing methods (7.5) Building symbol tables (7.6) How to use them to find multiply-declared and undeclared variables Type checking

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Paper 2917. Creating Variables: Traps and Pitfalls Olena Galligan, Clinops LLC, San Francisco, CA

Paper 2917. Creating Variables: Traps and Pitfalls Olena Galligan, Clinops LLC, San Francisco, CA Paper 2917 Creating Variables: Traps and Pitfalls Olena Galligan, Clinops LLC, San Francisco, CA ABSTRACT Creation of variables is one of the most common SAS programming tasks. However, sometimes it produces

More information

PES Institute of Technology-BSC QUESTION BANK

PES Institute of Technology-BSC QUESTION BANK PES Institute of Technology-BSC Faculty: Mrs. R.Bharathi CS35: Data Structures Using C QUESTION BANK UNIT I -BASIC CONCEPTS 1. What is an ADT? Briefly explain the categories that classify the functions

More information

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named

More information

Curriculum Map. Discipline: Computer Science Course: C++

Curriculum Map. Discipline: Computer Science Course: C++ Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code

More information

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A

More information

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ Answer the following 1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++ 2) Which data structure is needed to convert infix notations to postfix notations? Stack 3) The

More information

Passing 1D arrays to functions.

Passing 1D arrays to functions. Passing 1D arrays to functions. In C++ arrays can only be reference parameters. It is not possible to pass an array by value. Therefore, the ampersand (&) is omitted. What is actually passed to the function,

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

Basics of C++ and object orientation in OpenFOAM

Basics of C++ and object orientation in OpenFOAM Basics of C++ and object orientation in OpenFOAM To begin with: The aim of this part of the course is not to teach all of C++, but to give a short introduction that is useful when trying to understand

More information

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C Tutorial#1 Q 1:- Explain the terms data, elementary item, entity, primary key, domain, attribute and information? Also give examples in support of your answer? Q 2:- What is a Data Type? Differentiate

More information

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Dr. Martin O. Steinhauser University of Basel Graduate Lecture Spring Semester 2014 Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct Friday, 7 th March

More information

C++ Overloading, Constructors, Assignment operator

C++ Overloading, Constructors, Assignment operator C++ Overloading, Constructors, Assignment operator 1 Overloading Before looking at the initialization of objects in C++ with constructors, we need to understand what function overloading is In C, two functions

More information

BCS2B02: OOP Concepts and Data Structures Using C++

BCS2B02: OOP Concepts and Data Structures Using C++ SECOND SEMESTER BCS2B02: OOP Concepts and Data Structures Using C++ Course Number: 10 Contact Hours per Week: 4 (2T + 2P) Number of Credits: 2 Number of Contact Hours: 30 Hrs. Course Evaluation: Internal

More information

Basics of I/O Streams and File I/O

Basics of I/O Streams and File I/O Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading

More information

Classes and Pointers: Some Peculiarities (cont d.)

Classes and Pointers: Some Peculiarities (cont d.) Classes and Pointers: Some Peculiarities (cont d.) Assignment operator Built-in assignment operators for classes with pointer member variables may lead to shallow copying of data FIGURE 3-22 Objects objectone

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

C++FA 3.1 OPTIMIZING C++

C++FA 3.1 OPTIMIZING C++ C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have

More information

Lecture 12 Doubly Linked Lists (with Recursion)

Lecture 12 Doubly Linked Lists (with Recursion) Lecture 12 Doubly Linked Lists (with Recursion) In this lecture Introduction to Doubly linked lists What is recursion? Designing a node of a DLL Recursion and Linked Lists o Finding a node in a LL (recursively)

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

Cours de C++ Utilisations des conteneurs

Cours de C++ Utilisations des conteneurs Cours de C++ Utilisations des conteneurs Cécile Braunstein cecile.braunstein@lip6.fr 1 / 18 Introduction Containers - Why? Help to solve messy problems Provide useful function and data structure Consistency

More information

Analysis of a Search Algorithm

Analysis of a Search Algorithm CSE 326 Lecture 4: Lists and Stacks 1. Agfgd 2. Dgsdsfd 3. Hdffdsf 4. Sdfgsfdg 5. Tefsdgass We will review: Analysis: Searching a sorted array (from last time) List ADT: Insert, Delete, Find, First, Kth,

More information

recursion, O(n), linked lists 6/14

recursion, O(n), linked lists 6/14 recursion, O(n), linked lists 6/14 recursion reducing the amount of data to process and processing a smaller amount of data example: process one item in a list, recursively process the rest of the list

More information

Module 2 Stacks and Queues: Abstract Data Types

Module 2 Stacks and Queues: Abstract Data Types Module 2 Stacks and Queues: Abstract Data Types A stack is one of the most important and useful non-primitive linear data structure in computer science. It is an ordered collection of items into which

More information

Cpt S 223. School of EECS, WSU

Cpt S 223. School of EECS, WSU Abstract Data Types 1 Topics Abstract Data Types (ADTs) Some basic ADTs: Lists Stacks Queues 2 Primitive Data Type vs. Abstract Data Types Primitive DT: ADT: programmer progra ammer Interface (API) e.g.,

More information

Sequences in the C++ STL

Sequences in the C++ STL CS 311 Data Structures and Algorithms Lecture Slides Wednesday, November 4, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009 Glenn

More information

Linked List as an ADT (cont d.)

Linked List as an ADT (cont d.) Linked List as an ADT (cont d.) Default constructor Initializes list to an empty state Destroy the list Deallocates memory occupied by each node Initialize the list Reinitializes list to an empty state

More information

Linked Lists: Implementation Sequences in the C++ STL

Linked Lists: Implementation Sequences in the C++ STL Linked Lists: Implementation Sequences in the C++ STL continued CS 311 Data Structures and Algorithms Lecture Slides Wednesday, April 1, 2009 Glenn G. Chappell Department of Computer Science University

More information

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security & BSc. (Hons.) Software Engineering Cohort: BIS/05/FT BCNS/05/FT BSE/05/FT Examinations for 2005-2006 / Semester

More information

7.1 Our Current Model

7.1 Our Current Model Chapter 7 The Stack In this chapter we examine what is arguably the most important abstract data type in computer science, the stack. We will see that the stack ADT and its implementation are very simple.

More information

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c Lecture 3 Data structures arrays structs C strings: array of chars Arrays as parameters to functions Multiple subscripted arrays Structs as parameters to functions Default arguments Inline functions Redirection

More information

N3458: Simple Database Integration in C++11

N3458: Simple Database Integration in C++11 N3458: Simple Database Integration in C++11 Thomas Neumann Technische Univeristät München neumann@in.tum.de 2012-10-22 Many applications make use of relational database to store and query their data. However,

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

Illustration 1: Diagram of program function and data flow

Illustration 1: Diagram of program function and data flow The contract called for creation of a random access database of plumbing shops within the near perimeter of FIU Engineering school. The database features a rating number from 1-10 to offer a guideline

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C 1 An essential part of any embedded system design Programming 2 Programming in Assembly or HLL Processor and memory-sensitive

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from

More information

Variable Base Interface

Variable Base Interface Chapter 6 Variable Base Interface 6.1 Introduction Finite element codes has been changed a lot during the evolution of the Finite Element Method, In its early times, finite element applications were developed

More information

A Summary of Operator Overloading

A Summary of Operator Overloading A Summary of Operator Overloading David Kieras, EECS Dept., Univ. of Michigan Prepared for EECS 381 8/27/2013 Basic Idea You overload an operator in C++ by defining a function for the operator. Every operator

More information

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139

ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139 ECE 250 Data Structures and Algorithms MIDTERM EXAMINATION 2008-10-23/5:15-6:45 REC-200, EVI-350, RCH-106, HH-139 Instructions: No aides. Turn off all electronic media and store them under your desk. If

More information

sqlpp11 - An SQL Library Worthy of Modern C++

sqlpp11 - An SQL Library Worthy of Modern C++ 2014-09-11 Code samples Prefer compile-time and link-time errors to runtime errors Scott Meyers, Effective C++ (2nd Edition) Code samples Let s look at some code String based In the talk, we looked at

More information

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays. Arrays Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html 1 Grid in Assignment 2 How do you represent the state

More information

Sequential Program Execution

Sequential Program Execution Sequential Program Execution Quick Start Compile step once always g++ -o Realtor1 Realtor1.cpp mkdir labs cd labs Execute step mkdir 1 Realtor1 cd 1 cp../0/realtor.cpp Realtor1.cpp Submit step cp /samples/csc/155/labs/1/*.

More information

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

CHAPTER 4 ESSENTIAL DATA STRUCTRURES CHAPTER 4 ESSENTIAL DATA STRUCTURES 72 CHAPTER 4 ESSENTIAL DATA STRUCTRURES In every algorithm, there is a need to store data. Ranging from storing a single value in a single variable, to more complex

More information

Why you shouldn't use set (and what you should use instead) Matt Austern

Why you shouldn't use set (and what you should use instead) Matt Austern Why you shouldn't use set (and what you should use instead) Matt Austern Everything in the standard C++ library is there for a reason, but it isn't always obvious what that reason is. The standard isn't

More information

Syllabus OBJECT ORIENTED PROGRAMMING C++

Syllabus OBJECT ORIENTED PROGRAMMING C++ 1 Syllabus OBJECT ORIENTED PROGRAMMING C++ 1. Introduction : What is object oriented programming? Why do we need objectoriented. Programming characteristics of object-oriented languages. C and C++. 2.

More information

Top 72 Perl Interview Questions and Answers

Top 72 Perl Interview Questions and Answers Top 72 Perl Interview Questions and Answers 1. Difference between the variables in which chomp function work? Scalar: It is denoted by $ symbol. Variable can be a number or a string. Array: Denoted by

More information

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00 MPLAB TM C30 Managed PSV Pointers Beta support included with MPLAB C30 V3.00 Contents 1 Overview 2 1.1 Why Beta?.............................. 2 1.2 Other Sources of Reference..................... 2 2

More information

CSC230 Getting Starting in C. Tyler Bletsch

CSC230 Getting Starting in C. Tyler Bletsch CSC230 Getting Starting in C Tyler Bletsch What is C? The language of UNIX Procedural language (no classes) Low-level access to memory Easy to map to machine language Not much run-time stuff needed Surprisingly

More information

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is preceded by an equal sign d. its name has undereline 2. Associations

More information

Functions and Parameter Passing

Functions and Parameter Passing Chapter 5: Functions and Parameter Passing In this chapter, we examine the difference between function calls in C and C++ and the resulting difference in the way functions are defined in the two languages.

More information

ECS 165B: Database System Implementa6on Lecture 2

ECS 165B: Database System Implementa6on Lecture 2 ECS 165B: Database System Implementa6on Lecture 2 UC Davis, Spring 2011 Por6ons of slides based on earlier ones by Raghu Ramakrishnan, Johannes Gehrke, Jennifer Widom, Bertram Ludaescher, and Michael Gertz.

More information

Stacks. Linear data structures

Stacks. Linear data structures Stacks Linear data structures Collection of components that can be arranged as a straight line Data structure grows or shrinks as we add or remove objects ADTs provide an abstract layer for various operations

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies) Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies) Duration of Course: 6 Months Fees: Rs. 25,000/- (including Service Tax) Eligibility: B.E./B.Tech., M.Sc.(IT/ computer

More information

CSE 211: Data Structures Lecture Notes VII

CSE 211: Data Structures Lecture Notes VII CSE 211: Data Structures Lecture Notes VII LINKED LISTS In the previous lectures we have seen the representation of ordered lists using an array and sequential mapping. These representations had the property

More information

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference? Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function

More information

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014 CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages Nicki Dell Spring 2014 What is a Programming Language? A set of symbols and associated tools that translate (if necessary) collections

More information

A brief introduction to C++ and Interfacing with Excel

A brief introduction to C++ and Interfacing with Excel A brief introduction to C++ and Interfacing with Excel ANDREW L. HAZEL School of Mathematics, The University of Manchester Oxford Road, Manchester, M13 9PL, UK CONTENTS 1 Contents 1 Introduction 3 1.1

More information

CORBA Programming with TAOX11. The C++11 CORBA Implementation

CORBA Programming with TAOX11. The C++11 CORBA Implementation CORBA Programming with TAOX11 The C++11 CORBA Implementation TAOX11: the CORBA Implementation by Remedy IT TAOX11 simplifies development of CORBA based applications IDL to C++11 language mapping is easy

More information

Data Structures using OOP C++ Lecture 1

Data Structures using OOP C++ Lecture 1 References: 1. E Balagurusamy, Object Oriented Programming with C++, 4 th edition, McGraw-Hill 2008. 2. Robert Lafore, Object-Oriented Programming in C++, 4 th edition, 2002, SAMS publishing. 3. Robert

More information

Class 16: Function Parameters and Polymorphism

Class 16: Function Parameters and Polymorphism Class 16: Function Parameters and Polymorphism SI 413 - Programming Languages and Implementation Dr. Daniel S. Roche United States Naval Academy Fall 2011 Roche (USNA) SI413 - Class 16 Fall 2011 1 / 15

More information

Semantic Analysis: Types and Type Checking

Semantic Analysis: Types and Type Checking Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors

More information

Demonstrating a DATA Step with and without a RETAIN Statement

Demonstrating a DATA Step with and without a RETAIN Statement 1 The RETAIN Statement Introduction 1 Demonstrating a DATA Step with and without a RETAIN Statement 1 Generating Sequential SUBJECT Numbers Using a Retained Variable 7 Using a SUM Statement to Create SUBJECT

More information

6.S096 Lecture 1 Introduction to C

6.S096 Lecture 1 Introduction to C 6.S096 Lecture 1 Introduction to C Welcome to the Memory Jungle Andre Kessler Andre Kessler 6.S096 Lecture 1 Introduction to C 1 / 30 Outline 1 Motivation 2 Class Logistics 3 Memory Model 4 Compiling 5

More information

Chapter 3: Restricted Structures Page 1

Chapter 3: Restricted Structures Page 1 Chapter 3: Restricted Structures Page 1 1 2 3 4 5 6 7 8 9 10 Restricted Structures Chapter 3 Overview Of Restricted Structures The two most commonly used restricted structures are Stack and Queue Both

More information

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell

C Dynamic Data Structures. University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell C Dynamic Data Structures University of Texas at Austin CS310H - Computer Organization Spring 2010 Don Fussell Data Structures A data structure is a particular organization of data in memory. We want to

More information

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C Embedded Systems A Review of ANSI C and Considerations for Embedded C Programming Dr. Jeff Jackson Lecture 2-1 Review of ANSI C Topics Basic features of C C fundamentals Basic data types Expressions Selection

More information

Persistent Binary Search Trees

Persistent Binary Search Trees Persistent Binary Search Trees Datastructures, UvA. May 30, 2008 0440949, Andreas van Cranenburgh Abstract A persistent binary tree allows access to all previous versions of the tree. This paper presents

More information