Scope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable.

Size: px
Start display at page:

Download "Scope of Variables. In general, it is not a good practice to define many global variables. 1. Use global to declare x as a global variable."

Transcription

1 Scope of Variables The variables used in function m-files are known as local variables. Any variable defined within the function exists only for the function to use. The only way a function can communicate between other functions is through input arguments and the outputs it returns. Unlike local variables, global variables are available to all parts of a computer program. Use global to declare x as a global variable. In general, it is not a good practice to define many global variables. 1 For example, the universal constant, say,. 2 However, you have to take the responsibly of not changing its value. 1 This violets the modularity. 2 Planck constant = in Quantum theories. Zheng-Liang Lu 188 / 227

2 Example: Local Variables 1 clear; clc; 2 3 x = 0; 4 for i = 1 : 10 5 addone(x); 6 disp(x); 7 end 1 function addone(x) 2 x = x + 1; 3 end What are the numbers shown? If you want the sequence 1, 2,..., 10, then how can you do? (Local, global, persistent?) Zheng-Liang Lu 189 / 227

3 Example: Global Variable 1 function h = falling(t) 2 global GRAVITY 3 h = 1 / 2 * GRAVITY * t.ˆ 2; 4 end 1 clear; clc; 2 global GRAVITY 3 GRAVITY = 9.8; 4 y = falling(0 : 0.1 : 5); What if you take global out of the function? As a more robust alternative, redefine the function to accept GRAVITY as an input. Zheng-Liang Lu 190 / 227

4 Types of User-Defined Functions Primary functions and subfunctions Anonymous functions Nested functions Private functions Zheng-Liang Lu 191 / 227

5 Primary Functions and Subfunctions A function m-file may contain more than one user-defined function. The first defined function in the file is called the primary function, whose name is the same as the m-file name. All other functions in the file are called subfunctions. Subfunctions are normally visible only to the primary function and other subfunctions in the same file. Note that the order of the subfunctions does not matter, but function names must be unique within the m-file. Zheng-Liang Lu 192 / 227

6 Example 1 function [a c] = circle(r) % primary function 2 a = area(r); 3 c = perimeter(r); 4 end 5 6 function y = area(x) % subfunction 1 7 y = pi * x.ˆ 2; 8 end 9 10 function v = perimeter(u) % subfunction 2 11 v = 2 * pi * u; 12 end Zheng-Liang Lu 193 / 227

7 1 >> [a c] = circle(2) 2 3 a = c = Recall that if only one variable is assigned as output of the function, say, circle, then the area is returned while the perimeter is ignored. Zheng-Liang Lu 194 / 227

8 Example: Alternative to Infinite Loops 3 One subfunction can be called by other subfunctions in addition to the primary function. 1 function test1 2 fprintf('hi, there. This is test1.\n'); 3 test2; 4 end 5 6 function test2 7 fprintf('hi, there. This is test2.\n'); 8 test1; 9 end Notice that two subfunctions calling each other can lead to a loop, resulting a fatal crash. 3 Thanks to a lively class discussion (MATLAB-238) on June 14, Zheng-Liang Lu 195 / 227

9 Anonymous Functions Anonymous functions enable you to create a simple function without needing to create an m-file for it. Anonymous functions are so-called the function handles, defined For example, 1 >> f x.ˆ 2 + x + 1 % x.ˆ2 allows vectorization. 2 >> f([1 10]) 3 4 ans = Furthermore, you can make the existing function a function handle by using operator, for example, y Zheng-Liang Lu 196 / 227

10 You can create anonymous functions having more than one input. One anonymous function can call another to implement function composition. 1 >> f y) sqrt(x.ˆ 2 + y.ˆ 2); % f is a function... handle 2 >> g y) f(x, y).ˆ 2; % g is a composite function 3 >> g(3, 4) 4 5 ans = Zheng-Liang Lu 197 / 227

11 More Examples 6 Give input values, return a function handle. 4 For example, 1 function y = f(a, b, c) 2 y a * x.ˆ 2 + b * x + c; 3 end Give a function handle as input, return a value. 5 For example, 1 function y = diff(f, x) 2 eps = 1e-9; 3 y = (f(x + eps) - f(x))./ eps; 4 end Give a function handle as input, return a function handle? (Try.) 4 Contribution by Ms. Queenie Chang (MAT25108) on March 18, Thanks to a lively class discussion (MATLAB-260) on September 16, Thanks to a lively class discussion (MATLAB-244) on August 22, Zheng-Liang Lu 198 / 227

12 Nested Functions Functions are said to be nested if the functions are defined within the parent function. A nested function can access the variables of its parent function. 1 function f = parabola(a, b, c) 2 f %f is a function handle of p 3 function y = p(x) % p shares a, b, and c 4 y = a * x.ˆ2 + b * x + c; 5 end 6 end Zheng-Liang Lu 199 / 227

13 1 >> y = parabola(1, 2, 1); 2 >> y(5) 3 4 ans = Note that the nested functions are defined anywhere within the main function. (Why?) Zheng-Liang Lu 200 / 227

14 Private Functions Private functions are useful when you want to limit the scope of the function. A private functions resides in subfolder with the special name private. The private function is visible only to functions in the parent directory. Note that you cannot call the private function from the command line or from functions outside the parent of the private folder. Zheng-Liang Lu 201 / 227

15 Precedence When Calling Functions 1 Nested functions 2 Subfunctions within the same file 3 Private functions 4 Local functions in the same directory 5 Built-in functions 6 Standard m files in PATH Zheng-Liang Lu 202 / 227

16 Example: Bisection Method The bisection method in mathematics is a root-finding method that repeatedly bisects an interval and then selects a subinterval in which a root must lie for further processing. (Why?) It is often used to obtain an approximate solution. Zheng-Liang Lu 203 / 227

17 Zheng-Liang Lu 204 / 227

18 Outline for Bisection Method 1. At each step, the algorithm divides the interval in two by computing the midpoint c = (a + b)/2 of the interval and the value of the function f (c) at that point. 2. Unless c is itself a root (which is very unlikely, but possible), there are now two possibilities: either f (a) and f (c) have opposite signs and bracket a root, or f (c) and f (b) have opposite signs and bracket a root. Zheng-Liang Lu 205 / 227

19 3. The method selects the subinterval that is a bracket as a new interval to be used in the next step. 4. In this way the interval that contains a zero of f is reduced in width by 1 2 at each step. 5. The process is continued until the interval is sufficiently small. 7 7 How small? A certain number you give is to be the stop criteria. Zheng-Liang Lu 206 / 227

20 Problem Formulation Input - Target function f (x) - Endpoints of the interval [a, b] for any real numbers a < b - Minimal interval length ɛ = b a Output - the approximate root ˆr Note that a and b will be updated iteratively. Zheng-Liang Lu 207 / 227

21 Solution 1 clear; clc; format long; 2 3 a = input('a =?\n'); 4 b = input('b =?\n'); 5 f x.ˆ 3 - x - 2; % target function 6 eps = 1e-9; 7 iter = 0; % the number of iterations 8 9 if f(a) == 0 10 r = a; % lucky a 11 elseif f(b) == 0 12 r = b; % lucky b 13 else 14 while b - a > eps 15 iter = iter + 1; 16 c = (a + b) / 2; % middle point 17 if f(c) == 0 Zheng-Liang Lu 208 / 227

22 18 r = c; % lucky c 19 break; 20 elseif (f(a) * f(c) < 0) 21 b = c; 22 elseif (f(b) * f(c) < 0) 23 a = c; 24 else 25 error('failure: f(a) * f(c) > 0 and f(c) *... f(b) > 0.'); 26 end 27 fprintf('%d: %f\n', iter, c); 28 end 29 r = c % approximate solution 30 end Zheng-Liang Lu 209 / 227

23 c = Zheng-Liang Lu 210 / 227

24 Remarks Time complexity: O(log 2 n) What is n? In this case, n = b a. (Why?) ɛ So, it is an algorithm which runs in log time. This means that you need to make a trade-off between the numerical precision and the computation time. Be aware that this algorithm works well only with the premise that the behavior in [a, b] is mild. Approximate solutions may be significantly influenced by the initial interval [a, b]. 8 f (c) 0 but not equal to exactly 0. (Why?) 8 You may try another algorithm for the root finding problem, say, the Newton-Raphson method. Zheng-Liang Lu 211 / 227

25 Exercise Make your bisection method algorithm into a user-defined function, say, bisection. So, you can call bisection to find a root for a specific function in the command window or other programs. Besides, you should extend the function with more input arguments for parameters used in bisection. Zheng-Liang Lu 212 / 227

26 Problem Formulation Input - Target function f (x) - Endpoints of the interval [a, b] for any real numbers a < b - Minimal interval length ɛ = b a Output - The approximate root ˆr Zheng-Liang Lu 213 / 227

27 1 function r = bisection(f, a, b, eps) >> bisection(@(x) x.ˆ 3 - x - 2, 0, 3, 1e-9) 2 3 ans = Zheng-Liang Lu 214 / 227

28 Recursive Functions Recursion is when something is defined in terms of itself. A recursive function is a function that calls itself. Recursion is an alternative form of program control. It is essentially repetition without a loop. Zheng-Liang Lu 215 / 227

29 Example The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 4! = = 4 3! So we can say f (n) = n f (n 1), for n > 0. Also, we need a base case such that the recursion can stop instead of being an infinite loop. In this example, 0! = 1. Zheng-Liang Lu 216 / 227

30 Exercise Write a program which determines return a factorial of n. 1 function y = recursivefactorial(n) 2 if n > 0 3 y = n * recursivefactorial(n - 1); 4 else 5 y = 1; % base case 6 end 7 end We can use a loop to calculate n!. (Try.) Zheng-Liang Lu 217 / 227

31 Call Stack Zheng-Liang Lu 218 / 227

32 Equivalence 1 function y = loopfactorial(n) 2 y = 1; 3 for i = n : -1 : 1 4 y = y * i; 5 end 6 end One more intriguing question is, Can we always turn a recursive method into an iterative one? Yes, theoretically. 9 Which is better? 9 The Church-Turing thesis proves it if the memory serves. Zheng-Liang Lu 219 / 227

33 Example: Fibonacci Numbers 10 The Fibonacci sequence is a sequence with the following pattern: 0, 1, 1, 2, 3, 5, 8, 13, 21, Alternatively, the Fibonacci sequence is defined by the recurrence relation F n = F n 1 + F n 2, where F 0 = 0, F 1 = 1, and n 2. Given a positive integer n, determine F n. Input: n 0 Output: F n 10 See Fibonacci numbers. Zheng-Liang Lu 220 / 227

34 Solution 1 function y = recursivefib(n) 2 if n == 0 3 y = 0; 4 elseif n == 1 5 y = 1; 6 else 7 y = recursivefib(n - 1) + recursivefib(n - 2); 8 end 9 end It is a binary recursion, because there are two calls in the function. Time complexity: O(2 n ) (Why?) Can we implement a linear recursion for this problem? Zheng-Liang Lu 221 / 227

35 Alternative: Linear Recursion 1 function ret = linearfib(n) 2 ret = fib(0, 1, n); 3 function c = fib(a, b, n) % nested function 4 if n > 0 5 c = fib(b, b + a, n - 1); 6 else 7 c = a; 8 end 9 end 10 end Time complexity: O(n)! You can implement a loop version of this problem. (Try.) Zheng-Liang Lu 222 / 227

36 Fibinacci Numbers by Loops 1 function y = loopfib(n) 2 if n == 0 3 y = 0; 4 elseif n == 1 5 y = 1; 6 else 7 x = 0; 8 y = 1; 9 for i = 2 : n 10 tmp = x + y; 11 x = y; 12 y = tmp; 13 end 14 end 15 end Zheng-Liang Lu 223 / 227

37 Remarks Recursion bears substantial overhead. So, the recursive algorithm may execute a bit more slowly than the iterative equivalent. 11 Besides, a deeply recursive method depletes the call stack, which is limited, and causes a exception fast. 12 In practice, the decision whether to use recursion or iteration should be based on the nature of, and your understanding of, the problem you are trying to solve. 11 In modern compiler design, recursion elimination is automatic if the recurrence occurs in the last statement in the recursive function, so called tail recursion. However, only some of programming languages support the elimination of tail recursion. Unfortunately, Matlab does not support it. 12 Stack overflow. Zheng-Liang Lu 224 / 227

38 More Interesting Recursions Sum of numbers Product of numbers Greatest common divisor Towers of Hanoi Binary search Check whether a string is palindrome 13 using recursion 13 For example, noon, level, and radar. Zheng-Liang Lu 225 / 227

39 Computational Thinking 14 To think about computing, we need to be attuned to three fields: science, technology, and society. Computational thinking shares with mathematical thinking: the way to solve problems engineering thinking: the way to design and evaluating a large, complex system scientific thinking: the way to understand computability, intelligence, the mind and human behavior. 14 You should read this: Zheng-Liang Lu 226 / 227

40 The essence of computational thinking is abstraction. An algorithm is an abstraction of a step-by-step procedure for taking input and producing some desired output. A programming language is an abstraction of a set of strings each of which when interpreted effects some computation. And more. 15 The abstraction process - deciding what details we need to highlight and what details we can ignore - underlies computational thinking. The abstraction process also introduces layers. Well-defined interfaces between layers enable us to build large, complex systems. 15 For example, API and TCP/IP. Zheng-Liang Lu 227 / 227

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 172 / 225 Functions The first thing of the design of algorithms is to divide and conquer. A large and complex problem would be solved by couples

More information

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221

1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221 1 >> Lecture 3 2 >> 3 >> -- Functions 4 >> Zheng-Liang Lu 169 / 221 Functions Recall that an algorithm is a feasible solution to the specific problem. 1 A function is a piece of computer code that accepts

More information

Global Variables. ˆ Unlike local variables, global variables are available to all functions involved.

Global Variables. ˆ Unlike local variables, global variables are available to all functions involved. Global Variables ˆ Unlike local variables, global variables are available to all functions involved. ˆ Use global to declare x as global. ˆ For example, the universal constant, say,. 1 ˆ However, it is

More information

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226 Method Invocation Note that the input parameters are sort of variables declared within the method as placeholders. When calling the method, one needs to provide arguments, which must match the parameters

More information

The return Statement

The return Statement The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return

More information

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Exercise Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram. Zheng-Liang Lu Java Programming 197 / 227 1... 2 int[] hist = new int[5]; 3 //

More information

Recursion 1. Recursion is the process of defining something in terms of itself.

Recursion 1. Recursion is the process of defining something in terms of itself. Recursion 1 Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive. Recursion is an alternative form of program control. It is repetition

More information

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Variable Scope. The variable scope is the range of the program where the variable can be referenced. Variable Scope The variable scope is the range of the program where the variable can be referenced. Variables can be declared in class level, method level, and loop level. In general, a pair of curly brackets

More information

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A;

More information

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

1 class Lecture4 { 2 3 Loops / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 1 class Lecture4 { 2 3 "Loops" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207 Loops A loop can be used to make a program execute statements repeatedly without having

More information

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ). Chapter 8 Recursion CS: Java Programming Colorado State University Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem? There

More information

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ). /2/8 Chapter 8 Recursion CS: Java Programming Colorado State University Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem?

More information

Bisection method. we can implement the bisection method using: a loop to iterate until f(c) is close to zero a function handle to the function f

Bisection method. we can implement the bisection method using: a loop to iterate until f(c) is close to zero a function handle to the function f Bisection method we can implement the bisection method using: a loop to iterate until f(c) is close to zero a function handle to the function f 1 function [root] = bisect(f, a, b, tol) %BISECT Root finding

More information

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University Java Programming U Hou Lok Department of Computer Science and Information Engineering, National Taiwan University Java 272 8 19 Aug., 2016 U Hou Lok Java Programming 1 / 51 A Math Toolbox: Math Class The

More information

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1 RECURSION Chapter 5 Recursive Thinking Section 5.1 1 Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain kinds of problems that are difficult

More information

Selections. Zheng-Liang Lu 91 / 120

Selections. Zheng-Liang Lu 91 / 120 Selections ˆ Selection enables us to write programs that make decisions on. ˆ Selection structures contain one or more of the if, else, and elseif statements. ˆ The end statement denotes the end of selection

More information

Reals 1. Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method.

Reals 1. Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method. Reals 1 13 Reals Floating-point numbers and their properties. Pitfalls of numeric computation. Horner's method. Bisection. Newton's method. 13.1 Floating-point numbers Real numbers, those declared to be

More information

Arrays. ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be

Arrays. ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be Arrays ˆ An array, is a linear data structure consisting of a collection of elements, each identified by one array index. ˆ For math, arrays could be ˆ row vectors: u R 1 n for any positive integer n ˆ

More information

Recursion. Chapter 7

Recursion. Chapter 7 Recursion Chapter 7 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how to write recursive algorithms and methods for searching arrays To learn

More information

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano

Test Bank Ver. 5.0: Data Abstraction and Problem Solving with C++: Walls and Mirrors, 5 th edition, Frank M. Carrano Chapter 2 Recursion: The Mirrors Multiple Choice Questions 1. In a recursive solution, the terminates the recursive processing. a) local environment b) pivot item c) base case d) recurrence relation 2.

More information

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion 2. Recursion Algorithm Two Approaches to Algorithms (1) Iteration It exploits while-loop, for-loop, repeat-until etc. Classical, conventional, and general approach (2) Recursion Self-function call It exploits

More information

MATH2070: LAB 3: Roots of Equations

MATH2070: LAB 3: Roots of Equations MATH2070: LAB 3: Roots of Equations 1 Introduction Introduction Exercise 1 A Sample Problem Exercise 2 The Bisection Idea Exercise 3 Programming Bisection Exercise 4 Variable Function Names Exercise 5

More information

Recursion Chapter 3.5

Recursion Chapter 3.5 Recursion Chapter 3.5-1 - Outline Induction Linear recursion Example 1: Factorials Example 2: Powers Example 3: Reversing an array Binary recursion Example 1: The Fibonacci sequence Example 2: The Tower

More information

Example. Password generator

Example. Password generator Example Password generator Write a program which generates ten characters as a password. There may be lower-case letters, upper-case letters, and digital characters in the character sequence. Recall that

More information

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

Fundamentals of Programming Session 13

Fundamentals of Programming Session 13 Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Problem Solving (Computing) Array and Pointer

Problem Solving (Computing) Array and Pointer CS101 Introduction to computing Problem Solving (Computing) & Array and Pointer A. Sahu and S. V.Rao Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati 1 Outline Loop invariant and loop

More information

CS/CE 2336 Computer Science II

CS/CE 2336 Computer Science II S/E 2336 omputer Science II UT D Session 10 Recursion dapted from D Liang s Introduction to Java Programming, 8 th Ed 2 factorial(0) = 1; omputing Factorial factorial(n) = n*factorial(n-1); n! = n * (n-1)!

More information

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Common Errors 2 double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141 Generating random numbers Example Write a program which generates

More information

Calculus I Review Handout 1.3 Introduction to Calculus - Limits. by Kevin M. Chevalier

Calculus I Review Handout 1.3 Introduction to Calculus - Limits. by Kevin M. Chevalier Calculus I Review Handout 1.3 Introduction to Calculus - Limits by Kevin M. Chevalier We are now going to dive into Calculus I as we take a look at the it process. While precalculus covered more static

More information

Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank

Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank Data Abstraction & Problem Solving with C++: Walls and Mirrors 6th Edition Carrano, Henry Test Bank Download link: https://solutionsmanualbank.com/download/test-bank-for-data-abstractionproblem-solving-with-c-walls-and-mirrors-6-e-carrano-henry/

More information

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem Recursion Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem What is Recursion? A problem is decomposed into smaller sub-problems, one or more of which are simpler versions of

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

MATLAB Lecture 4. Programming in MATLAB

MATLAB Lecture 4. Programming in MATLAB MATLAB Lecture 4. Programming in MATLAB In this lecture we will see how to write scripts and functions. Scripts are sequences of MATLAB statements stored in a file. Using conditional statements (if-then-else)

More information

ECE 202 LAB 3 ADVANCED MATLAB

ECE 202 LAB 3 ADVANCED MATLAB Version 1.2 1 of 13 BEFORE YOU BEGIN PREREQUISITE LABS ECE 201 Labs EXPECTED KNOWLEDGE ECE 202 LAB 3 ADVANCED MATLAB Understanding of the Laplace transform and transfer functions EQUIPMENT Intel PC with

More information

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. Example Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct. 1... 2 Scanner input = new Scanner(System.in); 3 int x = (int) (Math.random()

More information

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion School of Electrical and Computer Engineering Cornell University revision: 2018-09-13-21-07 1 Dictionary Analogy 2 2 Computing Factorial

More information

ENGINEERING PROBLEM SOLVING WITH C++

ENGINEERING PROBLEM SOLVING WITH C++ ENGINEERING PROBLEM SOLVING WITH C++ Second Edition Delores M. Etter Electrical Engineering Department United States Naval Academy Jeanine A. Ingber Training Consultant Sandia National Laboratories Upper

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

From: Robert Sharpley Subject: Homeworks #6 Date: February 22, :09:53 AM EST Cc: Robert Sharpley

From: Robert Sharpley Subject: Homeworks #6 Date: February 22, :09:53 AM EST Cc: Robert Sharpley From: Robert Sharpley Subject: Homeworks #6 Date: February 22, 2006 9:09:53 AM EST Cc: Robert Sharpley %% Homework #5 - Solutions %% Here is a matlab code

More information

LECTURE 0: Introduction and Background

LECTURE 0: Introduction and Background 1 LECTURE 0: Introduction and Background September 10, 2012 1 Computational science The role of computational science has become increasingly significant during the last few decades. It has become the

More information

Lecture P6: Recursion

Lecture P6: Recursion Overview Lecture P6: Recursion What is recursion? When one function calls ITSELF directly or indirectly. Why learn recursion? Powerful programming tool to solve a problem by breaking it up into one (or

More information

Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

More information

Chapter 15: Recursion

Chapter 15: Recursion Chapter 15: Recursion Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 15 discusses the following main topics: Introduction to Recursion

More information

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved Recursion Chapter 7 Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an Array Recursively Processing a Linked Chain The Time Efficiency

More information

Question Points Score Total 100

Question Points Score Total 100 Name Signature General instructions: You may not ask questions during the test. If you believe that there is something wrong with a question, write down what you think the question is trying to ask and

More information

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

34. Recursion. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 34. Recursion Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Example: Factorials Example: Fibonacci Numbers Recursion vs. Iteration References Introduction Introduction Recursion

More information

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion? CH. 5 RECURSION ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OVERVIEW Recursion is an algorithmic

More information

Chapter 18 Recursion. Motivations

Chapter 18 Recursion. Motivations Chapter 18 Recursion CS1: Java Programming Colorado State University Original slides by Daniel Liang Modified slides by Chris Wilcox 1 Motivations Suppose you want to find all the files under a directory

More information

CS 310 Advanced Data Structures and Algorithms

CS 310 Advanced Data Structures and Algorithms CS 310 Advanced Data Structures and Algorithms Recursion June 27, 2017 Tong Wang UMass Boston CS 310 June 27, 2017 1 / 20 Recursion Recursion means defining something, such as a function, in terms of itself

More information

f( x ), or a solution to the equation f( x) 0. You are already familiar with ways of solving

f( x ), or a solution to the equation f( x) 0. You are already familiar with ways of solving The Bisection Method and Newton s Method. If f( x ) a function, then a number r for which f( r) 0 is called a zero or a root of the function f( x ), or a solution to the equation f( x) 0. You are already

More information

Arithmetic Compound Assignment Operators

Arithmetic Compound Assignment Operators Arithmetic Compound Assignment Operators Note that these shorthand operators are not available in languages such as Matlab and R. Zheng-Liang Lu Java Programming 76 / 141 Example 1... 2 int x = 1; 3 System.out.println(x);

More information

Binary floating point encodings

Binary floating point encodings Week 1: Wednesday, Jan 25 Binary floating point encodings Binary floating point arithmetic is essentially scientific notation. Where in decimal scientific notation we write in floating point, we write

More information

1.3. Conditional expressions To express case distinctions like

1.3. Conditional expressions To express case distinctions like Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

More information

Summary. csci 210: Data Structures Recursion. Recursive algorithms. Recursion. Topics READING:

Summary. csci 210: Data Structures Recursion. Recursive algorithms. Recursion. Topics READING: Summary csci 210: Data Structures Recursion Topics recursion overview simple eamples Sierpinski gasket counting blobs in a grid Hanoi towers READING: LC tetbook chapter 7 Recursion Recursive algorithms

More information

csci 210: Data Structures Recursion

csci 210: Data Structures Recursion csci 210: Data Structures Recursion Summary Topics recursion overview simple eamples Sierpinski gasket counting blobs in a grid Hanoi towers READING: LC tetbook chapter 7 Recursion A method of defining

More information

Decision-Making and Repetition

Decision-Making and Repetition 2.2 Recursion Introduction A recursive method is a method that call itself. You may already be familiar with the factorial function (N!) in mathematics. For any positive integer N, N! is defined to be

More information

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

More information

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

1 class Lecture3 { 2 3 Selections // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137 1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 89 / 137 Flow Controls The basic algorithm (and program) is constituted

More information

Bisecting Floating Point Numbers

Bisecting Floating Point Numbers Squishy Thinking by Jason Merrill jason@squishythinking.com Bisecting Floating Point Numbers 22 Feb 2014 Bisection is about the simplest algorithm there is for isolating a root of a continuous function:

More information

Reading 8 : Recursion

Reading 8 : Recursion CS/Math 40: Introduction to Discrete Mathematics Fall 015 Instructors: Beck Hasti, Gautam Prakriya Reading 8 : Recursion 8.1 Recursion Recursion in computer science and mathematics refers to the idea of

More information

AC : MATHEMATICAL MODELING AND SIMULATION US- ING LABVIEW AND LABVIEW MATHSCRIPT

AC : MATHEMATICAL MODELING AND SIMULATION US- ING LABVIEW AND LABVIEW MATHSCRIPT AC 2012-4561: MATHEMATICAL MODELING AND SIMULATION US- ING LABVIEW AND LABVIEW MATHSCRIPT Dr. Nikunja Swain, South Carolina State University Nikunja Swain is a professor in the College of Science, Mathematics,

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

V Advanced Data Structures

V Advanced Data Structures V Advanced Data Structures B-Trees Fibonacci Heaps 18 B-Trees B-trees are similar to RBTs, but they are better at minimizing disk I/O operations Many database systems use B-trees, or variants of them,

More information

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB: Contents VARIABLES... 1 Storing Numerical Data... 2 Limits on Numerical Data... 6 Storing Character Strings... 8 Logical Variables... 9 MATLAB S BUILT-IN VARIABLES AND FUNCTIONS... 9 GETTING HELP IN MATLAB...

More information

1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248

1 class Lecture6 { 2 3 Methods / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248 1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248 All roads lead to Rome. Anonymous 但如你根本並無招式, 敵人如何來破你的招式? 風清揚,

More information

II (Sorting and) Order Statistics

II (Sorting and) Order Statistics II (Sorting and) Order Statistics Heapsort Quicksort Sorting in Linear Time Medians and Order Statistics 8 Sorting in Linear Time The sorting algorithms introduced thus far are comparison sorts Any comparison

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

Recursion. Chapter 5

Recursion. Chapter 5 Recursion Chapter 5 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how to write recursive algorithms and methods for searching arrays To learn

More information

Algorithm. Building blocks of algorithm

Algorithm. Building blocks of algorithm UNIT I ALGORITHMIC PROBLEM SOLVING 9 Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation (pseudo code, flow chart, programming language), algorithmic problem

More information

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls. Jump Statements The keyword break and continue are often used in repetition structures to provide additional controls. break: the loop is terminated right after a break statement is executed. continue:

More information

Lecture Notes on Contracts

Lecture Notes on Contracts Lecture Notes on Contracts 15-122: Principles of Imperative Computation Frank Pfenning Lecture 2 August 30, 2012 1 Introduction For an overview the course goals and the mechanics and schedule of the course,

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:

More information

STATISTICS 579 R Tutorial: More on Writing Functions

STATISTICS 579 R Tutorial: More on Writing Functions Fall 2005 1. Iterative Methods: STATISTICS 579 R Tutorial: More on Writing Functions Three kinds of looping constructs in R: the for loop, the while loop, and the repeat loop were discussed previously.

More information

Loops / Repetition Statements

Loops / Repetition Statements Loops / Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops C has three kinds of repetition statements: the while loop the for

More information

Unit-5 Dynamic Programming 2016

Unit-5 Dynamic Programming 2016 5 Dynamic programming Overview, Applications - shortest path in graph, matrix multiplication, travelling salesman problem, Fibonacci Series. 20% 12 Origin: Richard Bellman, 1957 Programming referred to

More information

SECTION 5.1. Sequences

SECTION 5.1. Sequences SECTION 5.1 Sequences Sequences Problem: count number of ancestors one has 2 parents, 4 grandparents, 8 greatgrandparents,, written in a row as 2, 4, 8, 16, 32, 64, 128, To look for pattern of the numbers,

More information

V Advanced Data Structures

V Advanced Data Structures V Advanced Data Structures B-Trees Fibonacci Heaps 18 B-Trees B-trees are similar to RBTs, but they are better at minimizing disk I/O operations Many database systems use B-trees, or variants of them,

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

4.0 Programming with MATLAB

4.0 Programming with MATLAB 4.0 Programming with MATLAB 4.1 M-files The term M-file is obtained from the fact that such files are stored with.m extension. M-files are alternative means of performing computations so as to expand MATLAB

More information

SPARK-PL: Introduction

SPARK-PL: Introduction Alexey Solovyev Abstract All basic elements of SPARK-PL are introduced. Table of Contents 1. Introduction to SPARK-PL... 1 2. Alphabet of SPARK-PL... 3 3. Types and variables... 3 4. SPARK-PL basic commands...

More information

Handout 2 - Root Finding using MATLAB

Handout 2 - Root Finding using MATLAB Handout 2 - Root Finding using MATLAB Middle East Technical University MATLAB has couple of built-in root finding functions. In this handout we ll have a look at fzero, roots and solve functions. It is

More information

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion Lecture 13 1 What is? A method of programming in which a method refers to itself in order to solve a problem Never necessary In some situations, results in simpler and/or easier-to-write code Can often

More information

1. Find f(1), f(2), f(3), and f(4) if f(n) is defined recursively by f(0) = 1 and for n = 0, 1, 2,

1. Find f(1), f(2), f(3), and f(4) if f(n) is defined recursively by f(0) = 1 and for n = 0, 1, 2, Exercises Exercises 1. Find f(1), f(2), f(3), and f(4) if f(n) is defined recursively by f(0) = 1 and for n = 0, 1, 2, a) f(n + 1) = f(n) + 2. b) f(n + 1) = 3f(n). c) f(n + 1) = 2f(n). d) f(n + 1) = f(n)2

More information

1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244

1 class Lecture6 { 2 3 Methods // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244 1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 // keywords: 8 return Zheng-Liang Lu Java Programming 186 / 244 Methods 2 Methods can be used to define reusable code, and organize and simplify code. The idea

More information

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Logic is the anatomy of thought. John Locke ( ) This sentence is false. Logic is the anatomy of thought. John Locke (1632 1704) This sentence is false. I know that I know nothing. anonymous Plato (In Apology, Plato relates that Socrates accounts for his seeming wiser than

More information

Introduction to Programming I

Introduction to Programming I Still image from YouTube video P vs. NP and the Computational Complexity Zoo BBM 101 Introduction to Programming I Lecture #09 Development Strategies, Algorithmic Speed Erkut Erdem, Aykut Erdem & Aydın

More information

This session. Recursion. Planning the development. Software development. COM1022 Functional Programming and Reasoning

This session. Recursion. Planning the development. Software development. COM1022 Functional Programming and Reasoning This session Recursion COM1022 Functional Programming and Reasoning Dr. Hans Georg Schaathun and Prof. Steve Schneider University of Surrey After this session, you should understand the principle of recursion

More information

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

1 class Lecture3 { 2 3 Selections // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133 1 class Lecture3 { 2 3 "Selections" 4 5 } 6 7 // Keywords 8 if, else, else if, switch, case, default Zheng-Liang Lu Java Programming 88 / 133 Flow Controls The basic algorithm (and program) is constituted

More information

APPM 2460: Week Three For, While and If s

APPM 2460: Week Three For, While and If s APPM 2460: Week Three For, While and If s 1 Introduction Today we will learn a little more about programming. This time we will learn how to use for loops, while loops and if statements. 2 The For Loop

More information

switch-case Statements

switch-case Statements switch-case Statements A switch-case structure takes actions depending on the target variable. 2 switch (target) { 3 case v1: 4 // statements 5 break; 6 case v2: 7. 8. 9 case vk: 10 // statements 11 break;

More information

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO? 8/5/10 TODAY'S OUTLINE Recursion COMP 10 EXPLORING COMPUTER SCIENCE Revisit search and sorting using recursion Binary search Merge sort Lecture 8 Recursion WHAT DOES THIS CODE DO? A function is recursive

More information

Highlights. - Making threads. - Waiting for threads. - Review (classes, pointers, inheritance)

Highlights. - Making threads. - Waiting for threads. - Review (classes, pointers, inheritance) Parallel processing Highlights - Making threads - Waiting for threads - Review (classes, pointers, inheritance) Review: CPUs Review: CPUs In the 2000s, computing too a major turn: multi-core processors

More information

An introduction to Scheme

An introduction to Scheme An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

More information

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion CSC 148 Lecture 3 Dynamic Typing, Scoping, and Namespaces Recursion Announcements Python Ramp Up Session Monday June 1st, 1 5pm. BA3195 This will be a more detailed introduction to the Python language

More information

Symbol Tables Symbol Table: In computer science, a symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is

More information

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub I2204- Imperative Programming Schedule 08h00-09h40

More information

++x vs. x++ We will use these notations very often.

++x vs. x++ We will use these notations very often. ++x vs. x++ The expression ++x first increments the value of x and then returns x. Instead, the expression x++ first returns the value of x and then increments itself. For example, 1... 2 int x = 1; 3

More information

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling Recursion Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling With reference to the call stack Compute the result of simple recursive algorithms Understand

More information