Slide 1 Where are we, and where to go? Simple types of variables (variables=objects) 3 program structures (assignment, conditional, iteration) Static objects.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Factorial Recursion stack Binary Search Towers of Hanoi
Programming Recursion.
Local and Global Variables. COMP104 Local and Global / Slide 2 Scope The scope of a declaration is the block of code where the identifier is valid for.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Recursion COMP171 Fall Recursion / Slide 2 Recursion * In some problems, it may be natural to define the problem in terms of the problem itself.
Slide 1 Where are we, and where to go? Simple types of variables (variables=objects) 3 program structures (assignment, conditional, iteration) Static objects.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Searching Arrays. COMP104 Lecture 22 / Slide 2 Unordered Linear Search * Search an unordered array of integers for a value and return its index if the.
Slide 1 Where are we, and where to go? Simple types of variables (variables=objects) 3 program structures (assignment, conditional, iteration) Static objects.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Local, Global Variables, and Scope. COMP104 Slide 2 Functions are ‘global’, variables are ‘local’ int main() { int x,y,z; … } int one(int x, …) { double.
Simple Recursion. COMP104 Lecture 35 / Slide 2 Recursion: Example 0 * What does the following program do? #include using namespace std; int fac(int n){
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
1 Chapter 1 RECURSION. 2 Chapter 1  Subprogram implementation  Recursion  Designing Recursive Algorithms  Towers of Hanoi  Backtracking  Eight Queens.
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
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.
Problem Solving and Algorithms
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Chapter 12 Recursion, Complexity, and Searching and Sorting
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
CSE 1342 Programming Concepts Recursion. Overview of Recursion nRecursion is present when a function is defined in terms of itself. nThe factorial of.
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, ]
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
COMP102 Lab 121 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Basic Mathematics Chapter 1 (1.2 and 1.3) Weiss. Recursion / Slide 2 Logarithms * Definition: if and only if * Theorem 1.1: n Proof: apply the definition.
Math & Recursion COMP171 Fall Recursion / Slide 2 Logarithms * Definition: if and only if * Theorem 1.1: n Proof: apply the definition * Theorem.
ISOM MIS 215 Module 4 – Recursion. ISOM Where are we? 2 Intro to Java, Course Java lang. basics Arrays Introduction NewbieProgrammersDevelopersProfessionalsDesigners.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
Chapter 111 Recursion Chapter Objectives become familiar with the idea of recursion learn to use recursion as a programming tool become familiar.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
23 February Recursion and Logarithms CSE 2011 Winter 2011.
Introduction to Programming Lecture 6. Functions – Call by value – Call by reference Today's Lecture Includes.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
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! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
Function Recursion to understand recursion you must understand recursion.
Chapter 19: Recursion.
Recursion Version 1.0.
Chapter 15 Recursion.
5.13 Recursion Recursive functions Functions that call themselves
Chapter 15 Recursion.
Recursion and Logarithms
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursion.
Announcements Final Exam on August 19th Saturday at 16:00.
Pass by Reference.
Announcements Final Exam on December 25th Monday at 16:00.
Local, Global Variables, and Scope
7 Arrays.
Fundamental Programming
Chapter 18 Recursion.
ITEC324 Principle of CS III
Methods and Data Passing
Presentation transcript:

Slide 1 Where are we, and where to go? Simple types of variables (variables=objects) 3 program structures (assignment, conditional, iteration) Static objects Dynamic objects Functions on objects Procedural programming, Or structured programming, Or imperative programming (104), modularity (member) variables OOP (104, 151 ) Data structure: Linear: list, stack, queue Nonlinear: tree, graph Algorithms Algorithms+Data Structures = Programs Niklaus Wirth ( 171) (member) functions Array, struct pointer objects Data, variable, object Operation, function, procedure, subprogram, module, method operation class C, Pascal C++, Java ( 152)

Slide 2 Programming paradigms * Procedural programming * Object-oriented programming * Generic programming

Slide 3 int main() { int x,y,z; int a,b,c; a=f1(x); b=f2(y); c=f3(z); … } int f1() { } int f2() { } int f3() { } main(), is the first function, and is composed of a sequence of ‘procedures’ (or ‘functions’ in C++). Functions communicate by passing parameters. int main() { A a; B b; C c; a.f1(); b.f2(); c.f3(); … } Class A { Int x; Int f1(); } Class B { Int y; Int f2() } Class C { Int z; Int f3(); } procedural programming: Object oriented programming: a sequence of ‘objects’! Objects communicate by sending messages.

Slide 4 l Pass by value: formal parameters and arguments are different variables. ideal desirable behavior (but not efficient some times) l Pass by reference: they are the same variables, but different names! should carefully handled! Communication between functions:

Slide 5 Reference: X& l int& b a; l b is an alternative name for a void f(int& b) {}; int main() { int a; f(a); } int a=10; int& b = a; int& c = a; b = 100; a ??? int& b; 10 a b c Relationship with pointers (later on)!

Slide 6 int f(int x) { cout << “value of x = “ << x << endl; x = 4; } main() { int v = 5; f(v); cout << “value of v = “ << v << endl; } Output: Value of x = Value of v = n When a variable v is passed by value to a function f, its value is copied to the corresponding variable x in f n Any changes to the value of x does NOT affect the value of v n Call by value is the default mechanism for parameter passing in C Call by Value

Slide 7 int f(int& x) { cout << “value of x = “ << x << endl; x = 4; } main() { int v = 5; f(v); cout << “value of v = “ << v << endl; } Output: Value of x = Value of v = n When a variable v is passed by reference to a parameter x of function f, v and the corresponding parameter x refer to the same variable n Any changes to the value of x DOES affect the value of v 5 4 Call by Reference poor style of writing f(int &x)!

Slide 8 int f( const int& x ) { cout << “value of x = “ << x << endl; x = 4; // invalid } main() { int v = 5; f(v); cout << “value of v = “ << v << endl; } Passing variable v by constant reference to parameter x of f will NOT allow any change to the value of x. It is appropriate for passing large objects that should not be changed by the called function. Call by Constant Reference

Slide 9 * Call by value n for small objects that should not be changed by the function * Call by constant reference n for large objects that should not be changed by the function * Call by reference n is appropriate for all objects that may be changed by the function, n not recommended!!! rare! Parameter Passing Trade-off between the ‘ideal’ and ‘efficiency’!

Slide 10 * return by value, n for small objects that should not be changed by the function * return by constant reference, n for large objects that should not be changed by the function * return by reference, n for all objects that may be changed by the function, n not recommended!!! rare! Return Passing

Slide 11 Scope of variables The scope of a declaration is the block of code where the identifier is valid for use. n A global declaration is made outside the bodies of all functions and outside the main program. It is normally grouped with the other global declarations and placed at the beginning of the program file. n A local declaration is one that is made inside the body of a function. Locally declared variables cannot be accessed outside of the function they were declared in. Local to a function (the variables in Main are also local, local to ‘main’ function) n It is possible to declare the same identifier name in different parts of the program : local to a block Some code enclosed in braces

Slide 12 int main() { int x,y,z; … } void f() { int x; … } void f() { int x; x=1; { int x; x=2; cout << x << endl; } cout << x << endl; } int x; int main() { x=0; cout << x << endl; int x; x=1; { int x; x=2; cout << x << endl; } cout << x << endl; } Local to blocksLocal to functions Global (local to the file)

Slide 13 In a for-loop { int i; for (i=1;i<10;i++) cout << A[i]; } for (int i=1;i<10;i++) cout << A[i]; equivalent

Slide 14 Global Variables * Undisciplined use of global variables may lead to confusion and debugging difficulties. * Instead of using global variables in functions, try passing local variables by reference. It is forbidden in structured programming!

Slide 15 int MIN; void min(int,int); int main() { int x,y; cin >> x >> y >> endl; min(x,y); cout << MIN; } void min(int a, int b) { if (a<b) MIN=a; else MIN=b; } void min(int,int,int&); int main() { int x,y,mini; cin >> x >> y >> endl; min(x,y,mini); cout << mini; } void min(int a, int b, int& m) { if (a<b) m=a; else m=b; } int min(int,int); int main() { int x,y,mini; cin >> x >> y >> endl; mini=min(x,y); cout << mini; } int min(int a, int b) { int m; if (a<b) m=a; else m=b; return (m); } Summary Global variablePass by reference Pass by value Good style!!! Bad style!!!

Recursion Important for algorithm design and analysis l an illustrative example l a general problem solving method l technicality l recursion vs. iterations l examples

Slide 17 The tower of Hanoi Move a stack of disks of different sizes from one rod to another through a third one: - only one disk is moved each time - always smaller ones on top of bigger ones Check any webpage!

Slide 18 // move n disks from A to C via B void tower(int n, char A, char B, char C) { if (n==1) move(1,A,C); else {tower(n-1,A,C,B); move(n,A,C); tower(n-1,B,A,C)}; } void move(int k, char X, char Y) { cout << “move disc ” << k << “ from “ << X << “ to “ Y “ << endl; } More declarative than procedural! what vs. how

Slide 19 Trace tower(4,A,B,C)

Slide 20 Recursion: problem solving, therefore a programming technique * Recursion is one way to decompose a task into smaller subtasks. * At least one of the subtasks is a smaller example of the same task. * The smallest example of the same task has a non-recursive solution. A complex problem is often easier to solve by dividing it into several smaller parts (by top-down analysis), each of which can be solved by itself. The general top-down programming and problem solving: Example: The factorial function n! = n * (n-1) * (n-2) *... * 1 or n! = n * (n-1)! and 1! = 1

Slide 21 void three(…) { … } void two (…) { three(); } void one (…) { two(…); } void main() { one(…); } l Functions are calling (DIFFERENT) functions l One function (three) is the last ‘stopping function’ int fac(int n){ int product; if(n <= 1) product = 1; else product = n * fac(n-1); return product; } void main(){ fac(3); } l … calling the SAME function ( with different parameters) … l The ‘stopping function’ is already included as a ‘condition’ Normal (non-recursive) functions Recursive function

Slide 22 Recursive function A recursive function is just a function which is calling one (or more) other functions which happen to be the same!!! l Though the function is the same, ‘parameters’ are always ‘smaller’ l There is always at least one stopping case to terminate It is a kind of ‘loop’, even more powerful, as a general problem-solving technique! --- thinking recursively!

Slide 23 Everything is recursive … Linear search Length of a string Min, max of an array Selection sort Binary search: n Compare search element with middle element of the array: If not equal, then apply binary search to half of the array (if not empty) where the search element would be.

Slide 24 Recursion vs. Iteration (non-recursive) * A recursive solution may be simpler to write (once you get used to the idea) than a non-recursive solution.  But a recursive solution may not be as efficient as a non- recursive solution of the same problem. To iterate is human, to recurse, divine!

Slide 25 Start from the first element While (not yet finished) do do the current element move to the next one toto(n) If 0 or 1 element, just do it elsedecompose into first element and the n-1 remaining elements do the first element toto(n-1) For n elements:

Slide 26 Sum of the array Write a recursive function that takes a double array and its size as input and returns the sum of the array: if zero or one element, (trivial) sum( zero element or one element) = … ! else (decompose into 1-element and n-1 elements) sum(n elements) = sum( n-1 elements) + nth element

Slide 27 double asum(int a[], int size){ double sum; if(size==0) sum=0; else sum=asum(a,size-1)+a[size-1]; return sum; }

Slide 28 Product of an array Write a recursive function that takes a double array and its size as input and returns the product of the array: if zero or one element, (trivial) prod( zero element or one element) = …! else (decompose into 1-element and n-1 elements) prod(n elements) = prod(n-1 elements) * nth element

Slide 29 double aprod(int a[], int size) { doulbe prod; if(size==0) prod=1; else prod=aprod(a,size-1)*a[size-1]; return prod; }

Slide 30 Input: an array of integers A, and a value Output: the position of the value in the array if one element, check it! else decompose into 1-element and n-1 elements check the 1-element search(n-1) Linear search

Slide 31 int search(int A[], int size, int value) { int pos; if (size==1) if(A[size-1]==value) pos=1; else pos=-1; else if(A(size-1]==value) pos=size-1; else pos=search(A,size-1,value); return pos; }

Slide 32 Input: a sorted array of integers A, and a value Output: the position of the value in the array if the middle element == value, done! else if the middle element > value do the same in the first half of the array else do the same in the second half of the array } Binary search

Slide 33 int bsearch(int data[],lower,upper,value) { int pos; if (lower<=upper) { mid=(lower+upper)/ 2; if (data[mid] == value) pos=mid; else if (data[mid]>value) pos=bsearch(data,lower,mid–1,value); else pos=bsearch(data,mid+1,upper,value); } return pos; } Recursive binary search

Slide 34 int bsearch(int data[], int size, int value) { int lower, middle, upper; bool found; lower = 0; upper = size - 1; found=false; position=-1; while ((lower<=upper) && (!found)) { middle = (lower+upper)/2; if (data[middle] == value) { found=true; position=middle; } else { if (data[middle] > value) upper = middle - 1; else lower = middle + 1; } return position; } (iterative) Binary search: int main() { const int size=8; int data[size] = {1,5,6,7,9,10,17,30}; int value; cin >> value; cout << “position of the value is “ << bsearch(data,size,value) << endl; }

Slide 35 Take the minimum, then sort the remaining elements … Sorting