Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }



Similar documents
The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Section IV.1: Recursive Algorithms and Recursion Trees

What Is Recursion? Recursion. Binary search example postponed to end of lecture

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

10CS35: Data Structures Using C

csci 210: Data Structures Recursion

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

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

Recursion and Dynamic Programming. Biostatistics 615/815 Lecture 5

Analysis of Binary Search algorithm and Selection Sort algorithm

Data Structures. Algorithm Performance and Big O Analysis

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

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

Lecture Notes on Linear Search

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

Solving Problems Recursively

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

Pseudo code Tutorial and Exercises Teacher s Version

Recursive Algorithms. Recursion. Motivating Example Factorial Recall the factorial function. { 1 if n = 1 n! = n (n 1)! if n > 1

AP Computer Science Java Mr. Clausen Program 9A, 9B

PES Institute of Technology-BSC QUESTION BANK

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

Lecture 3: Finding integer solutions to systems of linear equations

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

8 Primes and Modular Arithmetic

Computer Science 210: Data Structures. Searching

Chapter 5. Recursion. Data Structures and Algorithms in Java

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

Sample Questions Csci 1112 A. Bellaachia

arrays C Programming Language - Arrays

Core Maths C1. Revision Notes

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

Regression Verification: Status Report

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

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

Exercises Software Development I. 11 Recursion, Binary (Search) Trees. Towers of Hanoi // Tree Traversal. January 16, 2013

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Mathematical Induction. Lecture 10-11

Example of a Java program

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

St S a t ck a ck nd Qu Q eue 1

8 Divisibility and prime numbers

MATH 289 PROBLEM SET 4: NUMBER THEORY

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Stacks. Linear data structures

Analysis of a Search Algorithm

CS 2412 Data Structures. Chapter 2 Stacks and recursion

Common Data Structures

Chapter 7: Additional Topics

Graduate Assessment Test (Sample)

Binary search algorithm

In mathematics, it is often important to get a handle on the error term of an approximation. For instance, people will write

Public Key Cryptography: RSA and Lots of Number Theory

Math 55: Discrete Mathematics

6. Standard Algorithms

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Lecture 12 Doubly Linked Lists (with Recursion)

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Continued Fractions and the Euclidean Algorithm

1 Review of Newton Polynomials

Catalan Numbers. Thomas A. Dowling, Department of Mathematics, Ohio State Uni- versity.

Recursion and Recursive Backtracking

Lecture 11: Tail Recursion; Continuations

C++ INTERVIEW QUESTIONS

COMPUTER SCIENCE. Paper 1 (THEORY)

Unit 6. Loop statements

Intermediate Math Circles March 7, 2012 Linear Diophantine Equations II

Assignment 5 - Due Friday March 6

3.5 RECURSIVE ALGORITHMS

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Year 9 set 1 Mathematics notes, to accompany the 9H book.

ML for the Working Programmer

ADVANCED SCHOOL OF SYSTEMS AND DATA STUDIES (ASSDAS) PROGRAM: CTech in Computer Science

Zero: If P is a polynomial and if c is a number such that P (c) = 0 then c is a zero of P.

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

CHAPTER 5. Number Theory. 1. Integers and Division. Discussion

Module 2 Stacks and Queues: Abstract Data Types

Data Structures. Topic #12

Algorithms. Margaret M. Fleck. 18 October 2010

Computations in Number Theory Using Python: A Brief Introduction

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

Factoring Trinomials: The ac Method

Basic Programming and PC Skills: Basic Programming and PC Skills:

3. Mathematical Induction

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Data Structures and Algorithms

NSM100 Introduction to Algebra Chapter 5 Notes Factoring

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

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

BCS2B02: OOP Concepts and Data Structures Using C++

Data Structure with C

Fibonacci numbers introduce vectors, functions and recursion.

Transcription:

Functions Recursion C++ functions Declare/prototype int myfunction (int ); Define int myfunction (int x){ int y = x*x; return y; Call int a; a = myfunction (7);

function call flow types type of function (of the return value) double myfunction (...) type of arguments double myfunction (int a, double b, char c) the types have to be consistent between declaration, definition and call

function arguments CALL DEFINITION arguments by value value is copied to parameter/argument parameters have the scope the function same as a local variable

return returns the function output value to the call instruction has to match function output type int myfunction (int x){ int y = x*x; return y; terminates the function even if there are more statements to exectute Argument default value if no argument is given at the call, use a default value default value given in function definition double log5(double x=125){......

Scope: local and global global : define outside any function visible everywhere (preserve value) local : define inside a function (or block) invisible outside the definition block Static variables static local variables do not get erased when function/ block terminates the next time the function is called, a static variable still has the previous value initialized only one time int function (int param){ static double myvar=0;//initialization happens only at the first function call... do something...

Overload function names myfunction does y = 2*x1-3*x2 I want it to work for doubles and int types int myfunction (int, int) double myfunction (double, double) double myfunction (int, double) double myfunction (double, int) Arguments by reference usually (call by value), if the argument passed to the function changes value inside the function, the variable used as argument does not. //call int a=0,b=0; b = f1(a);//now a=0, b=1 //function definition int f1 (int x){ x = x +1; return x; to modify the variable used as argument at the call, pass the argument by reference //call int a=0,b=0; b = f2(a); //now a=1, b=1 //function definition int f2 (int& x){ x = x +1; return x;

Recursive calls Recursion of a function A function that calls itself OR cyclic: function f calls function g; function g calls function f Creates a stack of calls Calls terminate in the reverse order of calling Local variables are defined independently for each call

Recursion: flow void message(int times){ if (times>0){ cout<< call t= <<times<< \n ; message(times-1); Solving a problem recursively recognize recursive/inductive nature many problems easier to solve with a loop build up the recursion mechanism follow the principle of mathematical induction most often, find an invariant operation can be a math formula can be an inductive form do one step of it, then call the recursion (or the other way) look carefully at the base cases

Sum of first n integers S(n) = 1 + 2 + 3 + 4 +.. + n = n(n+1)/2 induction : S(n) = S(n-1) + n = (n-1)*n/2 + n = n(n+1)/2 Sum of first n integers S(n) = 1 + 2 + 3 + 4 +.. + n = n(n+1)/2 induction : S(n) = S(n-1) + n = (n-1)*n/2 + n = n(n+1)/2 recursion int sum (int n){ if (n<0) { cout<< ERROR, negative ; return -1; if (n==0) return 0; return n + sum(n-1);

Factorial n! = 1 * 2 * 3 *... * n induction: n! = n* (n-1)! 1!=0!=1 can be very very large 10! = 3628800 50!! 3.0414* 10^64 Factorial long factorial (long n){ cout<< call: factorial( <<n< )\n ; int out; if(n<=1) out=1; else out = n*factorial(n-1); cout<< return: factorial( <<n< )\n ; return out;

Tower of Hanoi three towers/rods A, B, C A contains pegs 1 to n, in order, n at the bottom B, C empty TASK: move all pegs to A such that a peg at a time only top peg of a tower can move peg can sit only on higher value pegs Tower of Hanoi

Tower of Hanoi Tower of Hanoi

Tower of Hanoi Tower of Hanoi function f: moves top k pegs from tower X to tower Y leaves all pegs existing on Z and Y unmoved leaves all pegs on tower X below top k unmoved function f is recursive moves top k-1 pegs from X to Z (recursive call) moves k peg from X to Y moves top k-1 pegs from Z to Y (recursive call)

Euclid GCD given positive integers a and b find d=gcd(a,b) find integers m,n such that a*m + b*n = d. Do they always exist? recursion: if a>b and a=q*b+r then GCD(a,b) = GCD(b,r) what about m and n? Euclid GCD: find linear coefficients given positive integers a and b find d=gcd(a,b) find integers m,n such that a*m + b*n = d. Do they always exist? recursion: if a>b and a=q*b+r then GCD(a,b) = GCD(b,r) m(ab) = n(br) n(ab) = m(br)-q*n(br)

Fibonacci numbers Problem defined with recursion F(n+2) = F(n) + F(n+1) F(0) = 0; F(1) = 1 int Fibonacci (int n){ if (n<=1) return n; else return Fibonacci(n-1) + Fibonacci(n-2); Count characters preview the notion of ARRAY char s[200]; //array of 200 characters different type than class string can be accessed as s[0], s[1],..., s[199] s[0]= H ; s[1]= e ; s[2]= l ; s[3]= l ; s[4]= o ; char a = s[3]; works for any type double d[10]; int i[100]; C++ does not check for array bounds!!

Count characters start counting at position 1 record 1 if character find, keep looking at next position can be a loop can be a recursion Binary search Find a specific value V in a sorted array A[ ] Start with array indices i=0, j=last, m=middle Compare A[m] to V and decide where in the array to look next recursive call or a loop Why binary search and not simply check all elements?

Binary search How long is going to take? (worst case) In algorithms, how long means how many steps/instructions as a function of input n = size of array we dont want an exact time/value linear = like n = about CONSTANT * n quadratic = like n 2 = about CONSTANT * n 2 CONST*log n, CONST*n*log n, etc Binary Search takes CONSTANT*log(n) steps, in worst case