COMP171 Data Structures and Algorithm Tutorial 2 TA: M.Y.Chan.

Slides:



Advertisements
Similar presentations
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Advertisements

Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Recursion COMP171 Fall Recursion / Slide 2 Recursion * In some problems, it may be natural to define the problem in terms of the problem itself.
COMP171 Data Structure & Algorithm Tutorial 1 TA: M.Y.Chan.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compiling time * Dynamic Memory.
Recursion. Binary search example postponed to end of lecture.
Dynamic Objects. COMP104 Dynamic Objects / Slide 2 Memory Management * Static Memory Allocation n Memory is allocated at compilation time * Dynamic Memory.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Recursion.
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Standard Template Library C++ introduced both object-oriented ideas, as well as templates to C Templates are ways to write general code around objects.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Review for Midterm Chapter 1-9 CSc 212 Data Structures.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
CSIS 123A Lecture 9 Recursion Glenn Stevenson CSIS 113A MSJC.
Pointers OVERVIEW.
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Announcements Midterm1 is on this Tuesday at 19:40. Classrooms as follows: if (LastName
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CPS 100, Spring Tools: Solve Computational Problems l Algorithmic techniques  Brute-force/exhaustive, greedy algorithms, dynamic programming,
Data Structure and Algorithms. Algorithms: efficiency and complexity Recursion Reading Algorithms.
Templates “Generic Programming” ECE Templates A way to write code once that works for many different types of variables –float, int, char, string,
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
CompSci Review of Recursion with Big-Oh  Recursion is an indispensable tool in a programmer’s toolkit  Allows many complex problems to be solved.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Recursion.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
A Computer Science Tapestry 6.1 Classes: From Use to Implementation l We’ve used several classes, a class is a collection of objects sharing similar characteristics.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
C++ Programming Lecture 12 Functions – Part IV
Recursion in Java The answer to life’s greatest mysteries are on the last slide.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
CPS Today’s topics Programming Recursion Invariants Reading Great Ideas, p Brookshear, Section Upcoming Copyrights, patents, and.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
Motivation for Generic Programming in C++
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Announcements Final Exam on August 17th Wednesday at 16:00.
Pointers and dynamic objects
Using, Understanding, Updating, Designing and Implementing Classes
Announcements Final Exam on August 19th Saturday at 16:00.
Announcements Final Exam on December 25th Monday at 16:00.
Dynamic Objects.
Announcements HW3 grades will be announced this week
Pointers and dynamic objects
Chapter 13 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Dynamic Objects.
Presentation transcript:

COMP171 Data Structures and Algorithm Tutorial 2 TA: M.Y.Chan

A few words… Materials will be posted on the course homepage before the tutorials Please have a glance before the tutorials Please interrupt me if I’ve gone too fast Please don’t hesitate to ask questions in the tutorials

Today’s Outline A short revision (10 minutes) More on Class (15 minutes) Simple dynamic list (15 minutes) Recursion (40 minutes) Break (10 minutes) Template (10 minutes) Coding conventions (10 minutes)

A Short Revision Question on Pointer: What is printed by the following program? void PrintEquality(bool isEqual) { if (isEqual) cout << "Yes" << endl; else cout << "No" << endl; } int main(){ int * * p = new int * (new int(4)); int * q = *p; *q = 5; PrintEquality(p == &q); PrintEquality(*p == q); PrintEquality(**p == *q); } Easy question – you should be able to answer this within 2min

A Short Revision The answer is: 1) No2) Yes3) Yes But why?

More on Class From requirement to Implementation Example: a Dice class State & behavior State: depends on the physical properties Behavior: what the class does

More on Class Class Dice{ Public: Dice(int sides); // constructor int Roll(); // return the random roll int NumSides() const // how many sides this dies has Private: int myRollCount; // time die rolled int mySides; // sides on die } Behavior = public member function State = private data This header file is an interface to the class. It describe the behavior of the class, but not on how it is implemented

More on Class Header file provide information that programmers need to know to call a function & compiler can verify the correctness of the function call Implementation file (.cpp files) contains the details about implementation (function bodies)

More on Class #include “dice.h” #include “randgen.h” // implementation of dice class Dice::Dice(int sides) // postcondition: all private fields initialized { myRollCount = 0; mySide = sides; } Int Dice::Roll() // postcondition: number of rolls updated // random ‘die’ roll returned { RandGen gen; // random number generator myRollCount = myRollCount + 1; // update # of times die rolled return gen.RandInt(1,mySides); // in range [1.. mySide] }

More on Class Int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; } Int Dice:: NumRolls() const // postcondition: return # of times die has been rolled { return myRollCount; }

More on Class Create object by constructor Eg. Dice cube(6), Dice Dodeca(12) Dice (int sides) Int Roll() Int NumSides() const Int NumRolls() const ________________ myRollCount mySides 0 6 Private Public Behavior State Dice (int sides) Int Roll() Int NumSides() const Int NumRolls() const ________________ myRollCount mySides 0 12 Private Public Behavior State Cube(6) Dodeca(12)

More on Class Accessor functions – access the states but do not alter the state E.g. NumSides(), NumRolls() Always come with the keyword “const” Mutator functions – alter the state E.g. Roll() Tips: All state or instance variables in a class should be private

More on Class Inherit from other classes (base classes & derived classes) Allow easy software reuse (instead of re- inventing the wheels) Eg. extending the features of string such that it supports the "tokenizing“ feature (chop the string into words). Additional features: void Tokenize(); −−− chop the string into words int argSize(); −−−−− returns no. of words string arg(int k); −−−− returns the kth words

More on Class Expected behaviors: myString input; getline(cin, input); input.Tokenize(); for (int i = 0; i < input.argSize(); ++i) cout << input.arg(i) << endl;

More on Class class myString : public string { public: void Tokenize(); int argSize(); string arg(int k); private: vector arglist; } void myString::Tokenize() { istrstream s ( c_str() ); string temp; while (s >> temp) arglist.push_back(temp); } int myString::argSize() { return arglist.size(); } string myString::arg(int k) { return arglist[k]; } Base ClassDerived Class Inherits from string class and behaves like a string Additional member functions Additional data member c_str() is a member function of string that returns a "string literal“ version of itself. Note that myString inherits all the features of string; i.e., it can be used just like an ordinary string

A Simple Dynamic List Example cout << "Enter list size: "; int n; cin >> n; int *A = new int[n]; if(n<=0){ cout << "bad size" << endl; return 0; } initialize(A, n, 0); // initialize the array A with value 0 print(A, n); A = addElement(A,n,5); //add an element of value 5 at the end of A print(A, n); A = deleteFirst(A,n); // delete the first element from A print(A, n); selectionSort(A, n); // sort the array (not shown) print(A, n); delete [] A;

Initialize void initialize(int list[], int size, int value){ for(int i=0; i<size; i++) list[i] = value; }

print() void print(int list[], int size) { cout << "[ "; for(int i=0; i<size; i++) cout << list[i] << " "; cout << "]" << endl; }

Adding Elements // for adding a new element to end of array int* addElement(int list[], int& size, int value){ int* newList = new int [size+1]; // make new array if(newList==0){ cout << "Memory allocation error for addElement!" << endl; exit(-1); } for(int i=0; i<size; i++) newList[i] = list[i]; if(size) delete [] list; newList[size] = value; size++; return newList; }

Delete the first element // for deleting the first element of the array int* deleteFirst(int list[], int& size){ if(size <= 1){ if( size) delete list; size = 0; return NULL; } int* newList = new int [size-1]; // make new array if(newList==0){ cout << "Memory allocation error for deleteFirst!" << endl; exit(-1); } for(int i=0; i<size-1; i++)// copy and delete old array newList[i] = list[i+1]; delete [] list; size--; return newList; }

Adding Element (version 2) // for adding a new element to end of array void addElement( int * & list, int & size, const int value ){ int * newList = new int [size + 1]; if( newList == NULL ){ cout << "Memory allocation error for addElement!" << endl; exit(-1); } for( int i = 0; i < size; i++ ) newList[ i ] = list[ i ]; if( size ) delete [] list; newList[ size ] = value; size++; list = newList; return; }

Deleting Element (version 2) void deleteFirst( int * & list, int & size ){ if( size <= 1 ){ if( size ) delete list; list = NULL; size = 0; return; } delete list; // delete the first element list++; size--; return; }

Another Main program int main(){ int * A = NULL; int size = 0; int i; for( i = 0; i < 10; i++ ) addElement( A, size, i ); for( i = 0; i < 10; i++ ) cout << A[i] << " "; cout << endl; for( i = 0; i < 4; i++ ) deleteFirst( A, size ); for( i = 0; i < 6; i++ ) cout << A[i] << " "; cout << endl; return 0; }

Recursion Recursion is an indispensable tool in programmer’s toolkit It allow many complex problems to be solved simply Elegance and understanding in code often leads to better programs: easy to modify, extend and verify

Recursion Idea: to get help solving a problem from “coworkers” (clones) who work and act like you do Ask clone to solve a simpler (smaller) but similar problem Use clone’s result to put together your answer Need both concepts: call on the clone and use the result

Recursive function design principle Recursive functions have two key attributes There is a base case, which does not make a recursive call All other cases make a recursive call, with some parameter or other measure that decreases or moves towards the base case Ensure that sequence of calls eventually reaches the base case (converge) "Measure" can be tricky, but usually it’s straightforward

Recursive function design principle int recur_fn(parameters){ if(stopping condition) return stopping value; // other stopping conditions if needed return function of recur_fn(revised parameters) } Note: you can have more than one stopping condition and additional task can be done before or after the invocation of clone

Recursion Theoretically speaking, you can replace all the for- and while- loops by recursions However, it may not be the most efficient solution

Recursion Example 1: How to print words entered, but in reverse order? Possible solution: we can use a array to store all the words and print in reverse order. The array is probably the best approach, but recursion works too…

Recursion Explanation: Deploy the task to the coworker. Ask the clone to deliver the result first and we print the current word later.

Recursion Sometime recursion is not appropriate, when it is bad, it can be very bad – every tool requires knowledge and experience in how to use it Example: Fibonacci numbers

Recursion Example 2: Fibonacci numbers (discussed in the lecture) How many clone/calls to compute Fib(5)?

Recursion Answer: 15 A Huge number of function invocations result in overhead and memory usage Iterative approach is preferred

Break 10 minutes break Remember to come back !! Don’t escape from this tutorials !! Thanks

Recursion Recursion is not that bad !!!!! Can you still remember the example of Exponential fun ? int exp(int numb, int power){ if(power ==0) return 1; return numb * exp(numb, power -1); }

Recursion Is it the best? … How about this

Recursion Much faster than the previous solution How about iterative method? The power of recursion !!! It is different from our conventional way of calculation (ie. Iterative approach) Later, you will learn more about algorithm analysis -> how “good” the method is. The most efficient way to do recursion is to break down the task evenly and distribute to the coworkers and significantly “decrease” the size of the task in each recursion

Recursion Another example from your textbook (P.38 Ex.1.5) Question: Write a recursive function that returns the number of 1’s in the binary representation of N. Use the fact that this is equal to the number of 1’s in the representation of N/2, plus 1, if N is odd.

Recursion Consider: 1.Long Division 2.Binary representation  You will get some idea of the hint and know more about how to change the iterative approach to recursions

Recursion Straight-forward How to print the binary representation of a given integer?

Recursion void print(int n) { // base case if ( n==1 ) { cout << 1; return; } print(n/2); if ( n%2 == 1 ) cout << 1; else cout << 0; }

Recursion You can try out the questions in your textbook Get enough practices

Recursion Sometimes you may be asked to tell the meaning of a given recursive function What is the output of the function call f(3429)? void f(int x) { if (x < 10) cout << x; else { cout << x % 10; f( x / 10 ); }

Recursion Another Question: What is the value of the function call g(29039)? int g(int x) { if ( x < 10 ) return 1; else return g( x / 10 ) + 1; } The question can be more complicated if it involves two different recursive function which invoke each other recursively. Hope you will find this interesting questions in the future, but not in the exam.

Template Problem: We wrote a function for adding two integer values. However, if we want other functions for adding two values of other types, do we need to write a function for each of them? Of course, Reinventing your source code every time doesn’t seem like a very intelligent approach with a language that touts reusability

Template no longer holds a generic base class, but instead it holds an unspecified parameter. When you use a template, the parameter is substituted by the compiler

Template Template syntax The template keyword tells the compiler that the class definition that follows will manipulate one or more unspecified types

Coding Convention Programming style Useful link: Standard.html