A Computer Science Tapestry 1.1 What is Computer Science? What is it that distinguishes it from the separate subjects with which it is related? What is.

Slides:



Advertisements
Similar presentations
Part IV: Memory Management
Advertisements

Programming Languages Marjan Sirjani 2 2. Language Design Issues Design to Run efficiently : early languages Easy to write correctly : new languages.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Software Engineering and Design Principles Chapter 1.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
COSC 120 Computer Programming
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Introduction to a Programming Environment
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles C/C++ Emery Berger and Mark Corner University of Massachusetts.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 ES 314 Advanced Programming Lec 2 Sept 3 Goals: Complete the discussion of problem Review of C++ Object-oriented design Arrays and pointers.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
CompSci 100E 7.1 Solving Problems: Anagrams/Jumbles  How do humans solve puzzles like that at  Is it important to get computers.
CPS What is Computer Science? What is it that distinguishes it from the separate subjects with which it is related? What is the linking thread.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
By – Tanvir Alam.  This tutorial offers several things.  You’ll see some neat features of the language.  You’ll learn the right things to google. 
 200 Total Points ◦ 74 Points Writing Programs ◦ 60 Points Tracing Algorithms and determining results ◦ 36 Points Short Answer ◦ 30 Points Multiple Choice.
A Computer Science Tapestry 11.1 From practice to theory and back again In theory there is no difference between theory and practice, but not in practice.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Programming With C.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Pointers OVERVIEW.
Software Design 8.1 A Rose by any other name…C or Java? l Why do we use Java in our courses (royal we?)  Object oriented  Large collection of libraries.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
CompSci CompSci 6 Programming Design and Analysis I Dietolf (Dee) Ramm
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Object-Oriented Programming in C++
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Software Design 14.1 CPS 108 l Object oriented design and programming of medium-sized projects in groups using modern tools and practices in meaningful.
CPS What is Computer Science? What is it that distinguishes it from the separate subjects with which it is related? What is the linking thread.
CPS Heaps, Priority Queues, Compression l Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  What property of MP3 was a significant.
CPS What is Computer Science? What is it that distinguishes it from the separate subjects with which it is related? What is the linking thread.
 200 Total Points ◦ 75 Points Writing Programs ◦ 60 Points Tracing Algorithms and determining results ◦ 35 Points Short Answer ◦ 30 Points Multiple Choice.
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
CompSci Analyzing Algorithms  Consider three solutions to SortByFreqs, also code used in Anagram assignment  Sort, then scan looking for changes.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
A Computer Science Tapestry 10.1 From practice to theory and back again In theory there is no difference between theory and practice, but not in practice.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CompSci 100e 8.1 Scoreboard l What else might we want to do with a data structure? AlgorithmInsertionDeletionSearch Unsorted Vector/array Sorted vector/array.
A Computer Science Tapestry 12.1 Pointers, Memory, Abstractions l A pointer is the a variable/value that is a memory address  Addresses like 1, 2, 3,
CPS Heaps, Priority Queues, Compression l Compression is a high-profile application .zip,.mp3,.jpg,.gif,.gz, …  Why is compression important?
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
CPS What's a pointer, why good, why bad? l Pointer is a memory address, it's an indirect reference to memory or an object.  Rather than say we.
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
A Computer Science Tapestry 8.1 Vectors l Vectors are homogeneous collections with random access ä Store the same type/class of object, e.g., int, string,
CPS What is Computer Science? What is it that distinguishes it from the separate subjects with which it is related? What is the linking thread.
CPS Searching, Maps, Tables l Searching is a fundamentally important operation ä We want to do these operations quickly ä Consider searching using.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
A Computer Science Tapestry 8.1 Vectors l Vectors are homogeneous collections with random access  Store the same type/class of object, e.g., int, string,
Data Structures and Algorithm Analysis Dr. Ken Cosh Linked Lists.
CPS Searching, Maps, Tables (hashing) l Searching is a fundamentally important operation  We want to search quickly, very very quickly  Consider.
CompSci Toward understanding data structures  What can be put in a TreeSet?  What can be sorted?  Where do we find this information?  How do.
Java Arrays Fixed size, once created
Anagrams/Jumbles How do humans solve puzzles like that at
Announcements Final Exam on August 17th Wednesday at 16:00.
From practice to theory and back again
Data Structures & Algorithms
Fundaments of Game Design
Pointers, Memory, Abstractions
Program Design and Analysis II Professor: Jeffrey Forbes
Presentation transcript:

A Computer Science Tapestry 1.1 What is Computer Science? What is it that distinguishes it from the separate subjects with which it is related? What is the linking thread which gathers these disparate branches into a single discipline? My answer to these questions is simple --- it is the art of programming a computer. It is the art of designing efficient and elegant methods of getting a computer to solve problems, theoretical or practical, small or large, simple or complex. C.A.R. (Tony)Hoare

A Computer Science Tapestry 1.2 Why is programming fun? What delights may its practitioner expect as a reward? First is the sheer joy of making things Second is the pleasure of making things that are useful Third is the fascination of fashioning complex puzzle-like objects of interlocking moving parts Fourth is the joy of always learning Finally, there is the delight of working in such a tractable medium. The programmer, like the poet, works only slightly removed from pure thought- stuff. Fred Brooks

A Computer Science Tapestry 1.3 Efficient Programming l Designing and building efficient programs efficiently requires knowledge and practice  Hopefully the programming language helps, it’s not intended to get in the way  Object-oriented concepts, and more general programming concepts help in developing programs  Knowledge of data structures and algorithms helps l Tools of the engineer/scientist programmer  A library or toolkit is essential, don’t reinvent the wheel  Someone must build the tools  Programming is not just art, not just science, not just engineering

A Computer Science Tapestry 1.4 See readwords.cpp l This reads words, how can we count different/unique words? tvector list; string filename,word; cin >> filename; ifstream input(filename.c_str()); CTimer timer; timer.Start(); while (input >> word) { list.push_back(word); } timer.Stop(); cout << "read " << list.size() << " words in "; cout << timer.ElapsedTime() << " seconds" << endl;

A Computer Science Tapestry 1.5 Tracking different/unique words l We want to know how many times ‘the’ occurs  Do search engines do this? Does the number of occurrences of “basketball” on a page raise the priority of a webpage in some search engines? Downside of this approach for search engines? l Constraints on solving this problem  We must read every word in the file (or web page)  We must search to see if the word has been read before  We must process the word (bump a count, store the word)  Are there fundamental limits on any of these operations? Where should we look for data structure and algorithmic improvements?

A Computer Science Tapestry 1.6 Search: measuring performance l How fast is fast enough? bool search(const tvector & a, const string & key) // pre: a contains a.size() entries // post: return true if and only if key found in a { int k; int len = a.size(); for(k=0; k < len; k++) if (a[k] == key) return true; return false; } l C++ details: parameters? Return values? Vectors? l How do we measure performance of code? Of algorithm?  Does processor make a difference? PIII, G4, ???

A Computer Science Tapestry 1.7 Structuring data: sortreadwords.cpp l Search for a word using binary search  Differences from sequential/linear search?  What’s a precondition for binary search to work? l How can we store new words so that binary search will work?  Add to end of vector and sort the vector  Add to end of vector and shift (down) until location found  Advantages of one method over another? l What about the C++ details in using a struct/class to store data, how are comparisons made?

A Computer Science Tapestry 1.8 Review/Preview: Anagrams/Jumbles l Brute-force approach to finding anagrams/solving Jumbles  Brute-force often thought of as “lack of thought”  What if the better way requires too much thought?  What if there’s nothing better? l nelir,nelri, neilr, neirl, nerli, neril, nleir, nleri, nlier, nlire, nlrei, nlrie, nielr, nierl, niler, nilre, nirel, … lenir, lenri, leinr, leirn, lerni, lerin, liner  What’s the problem here?  Is there a better method?

A Computer Science Tapestry 1.9 Brute force? permana.cpp // find anagram of word in wordSource // list is a vector [0, 1, 2, …, n] Permuter p(list); int count = 0; string copy(word);// makes copy the right length for(p.Init(); p.HasMore(); p.Next()) { p.Current(list); for(k=0; k < list.size(); k++) { copy[k] = word[list[k]]; } if (wordSource.contains(copy)) { cout << "anagram of " << copy << endl; break; // find first anagram only }

A Computer Science Tapestry 1.10 Quantifying brute force for anagrams l On one machine make/test a word takes seconds/word  9! is 362,880, how long does this take?  What about a ten-letter word? l We’re willing to do some pre-processing to make the time to find anagrams quicker  Often find that some initialization/up-front time or cost saves in the long run  We need a better method than trying all possible permutations  What properties do words share that are anagrams?

A Computer Science Tapestry 1.11 Preliminaries: C++ in permana.cpp l What is a dictionary?  What is a class, what are the methods, why use it?  What properties of the class do methods depend on, class invariants? l What is a tvector and why is it used instead of an array?  How are elements added to the vector?  Differences between tvector and vector (STL class)? l What is a Permuter and how does it work?  Where is information about this class found?  What patterns of use does a permuter exhibit?

A Computer Science Tapestry 1.12 Toward a faster anagram finder l Words that are anagrams have the same letters; use a letter fingerprint or signature to help find anagrams  Count how many times each letter occurs: “teacher” “cheater” l Store words, but use fingerprint for comparison when searching for an anagram  How to compare fingerprints using operator ==  How to compare fingerprints using operator < l How do we make client programmers unaware of fingerprints? Should we do this?

A Computer Science Tapestry 1.13 OO and C++ features we’ll use l We’ll use an adapter or wrapper class called Anaword instead of a string  Clients can treat Anaword objects like strings, but the objects are better suited for finding anagrams than strings  The Anaword for “bear” prints as “bear” but compares to other Anaword objects as l C++ allows us to overload operators to help, not necessary but good cosmetically  Relational operators == and < What about other operators: >, =, and !=  Stream operator << l How should we implement overloaded operators?

A Computer Science Tapestry 1.14 Pointers l Pointers are essential in many programming applications  Indirect references are often useful Publish your as but forward it to wherever you “really” are as you change jobs, for  Allow data to be shared rather than duplicated Sort a list of people/grades by name and by grade, we can maintain one list of people, and two lists of indexes, one sorted by name, one sorted by grade  Facilitate inheritance Essential for OO  Implement data structures Lists, trees, … Joe Smith 90 Sue Johson 87 Pat Murphy 95

A Computer Science Tapestry 1.15 Pointer basics l Memory is allocated dynamically at runtime from the heap  Contrast to statically allocated at compile time Static variables take up space on the runtime stack, program executable may be large as a result Scores isn’t 20x bigger than y, why? l Pointers reference memory, a pointer is different from the object it points to. There is a pointer and a pointee. Date d string s int y scores void foo(const Date& d) { string s; int y; tvector scores(20); }

A Computer Science Tapestry 1.16 Syntax and semantics of pointers void foo() { string s("hello"); string * sp = new string("world"); string * sp2; // never do this!!! int slen = s.length(); int splen = sp->length(); // splen = (*sp).length(); int splen2 = sp2->length(); } l Memory allocated dynamically using new  What happens to s when foo terminates? l Dereference a pointer using *, get at the object pointed to  a-> is shorthand for (*a). l Pointers that don’t point at something are BIG TROUBLE

A Computer Science Tapestry 1.17 Pointer/Pointee confusion? l Pass-by-value, can we change the parameter? void doStuff(Date * d) void doStuff2(Date * d) { d = new Date(); *d += 1; } Date * flagDay = new Date(6,14,2001); doStuff(flagDay); cout << *flagDay << endl; l In case things aren’t confusing enough  const Date * d; // pointee is constant  Date * const d; // pointer is constant

A Computer Science Tapestry 1.18 Vectors of pointers void readWords(istream& input, tvector & list) // post: all words in input stored in list { string word; while (input >> word) { list.push_back(word); } cout << "read " << list.size() << " words" << endl; } What changes if we use tvector instead? l What happens if we use code below which uses the address-of operator for vector of pointers (don’t do this at home) list.push_back(&word);

A Computer Science Tapestry 1.19 Sidebar: implementing swap in C l Unlike C++, there are no reference parameters in C  Simulate pass-by-reference using pointers, what happens to actual parameters x and y in code below? void swap(string& a, string& b) { string temp = a; a = b; b = a; } int main() { string x("first"), y("second"); swap(x, y); }

A Computer Science Tapestry 1.20 Implementing swap in C l In C we must pass pointers, and use address-of operator to simulate reference parameters, is the picture different ?  In C++ the pointers are hidden, harder to make mistakes? void swap(string * a, string * b) { string temp = *a; *a = *b; *b = temp; } int main() { string x("first"), y("second"); swap(&x, &y); }

A Computer Science Tapestry 1.21 Flexibility l About Linux compared to Windows  “ All this flexibility comes with a price : complexity. Many vendors are realizing that ease of use is paramount for most and have developed standard "distributions" consisting of Linux bundled with a wide range of necessary software, from word processors and spreadsheets to personal organizers. Some of these distributions are: RedHat (perhaps the best known), SuSE, Debian, Slackware and Mandrake.”

A Computer Science Tapestry 1.22 Flexibility l About FPGAs compared to general computers  “The most common type of computing system is the general- purpose processor. Under this model, the hardware of the system is limited to merely a few basic tasks. By combining and building off of these operations, a general-purpose computer can perform a much larger number of operations than it was originally designed to handle. Which is why the general- purpose computer is so flexible. However this flexibility comes with a price. For any specific application, the general-purpose processor will perform poorly when compared to a custom hardware implementation”