Iosif Ignat, Marius Joldoș Laboratory Guide 12. Recursion RECURSION

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

Chapter 5. Recursion. Data Structures and Algorithms in Java

10CS35: Data Structures Using C

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

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

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

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

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

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

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

West Virginia University College of Engineering and Mineral Resources. Computer Engineering 313 Spring 2010

Recursion and Recursive Backtracking

PES Institute of Technology-BSC QUESTION BANK

Section IV.1: Recursive Algorithms and Recursion Trees

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

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

Computer Science 2nd Year Solved Exercise. Programs 3/4/2013. Aumir Shabbir Pakistan School & College Muscat. Important. Chapter # 3.

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

Mathematical Induction

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

There are six different windows that can be opened when using SPSS. The following will give a description of each of them.

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

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

PARALLELIZED SUDOKU SOLVING ALGORITHM USING OpenMP

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

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

Algorithm Design and Recursion

csci 210: Data Structures Recursion

Module 2 Stacks and Queues: Abstract Data Types


2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

Data Structure with C

2 SYSTEM DESCRIPTION TECHNIQUES

2. (a) Explain the strassen s matrix multiplication. (b) Write deletion algorithm, of Binary search tree. [8+8]

Stacks. Linear data structures

Computer Systems Architecture

Chapter One Introduction to Programming

Solving Systems of Linear Equations Using Matrices

Patterns in Pascal s Triangle

Java Program Coding Standards Programming for Information Technology

Introduction to MATLAB IAP 2008

Arithmetic and Algebra of Matrices

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

For another way to generate recursive sequences, see Calculator Note 1D.

Special Notice. Rules. Weiss Schwarz Comprehensive Rules ver Last updated: October 15 th Outline of the Game

Base Conversion written by Cathy Saxton

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

CS 2412 Data Structures. Chapter 2 Stacks and recursion

Data Structures. Algorithm Performance and Big O Analysis

Lecture 3: Finding integer solutions to systems of linear equations

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Multiplication. Year 1 multiply with concrete objects, arrays and pictorial representations

LAYOUT OF THE KEYBOARD

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Unit 6. Loop statements

Sequence of Numbers. Mun Chou, Fong QED Education Scientific Malaysia

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:

Math 181 Handout 16. Rich Schwartz. March 9, 2010

Chapter 3. Distribution Problems. 3.1 The idea of a distribution The twenty-fold way

Just the Factors, Ma am

System Interconnect Architectures. Goals and Analysis. Network Properties and Routing. Terminology - 2. Terminology - 1

Basic Use of the TI-84 Plus

Arrays in Java. Working with Arrays

MATH Fundamental Mathematics IV

In this Chapter you ll learn:

Binary Trees and Huffman Encoding Binary Search Trees

Optimizations. Optimization Safety. Optimization Safety. Control Flow Graphs. Code transformations to improve program

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

Stack Allocation. Run-Time Data Structures. Static Structures

Automata and Computability. Solutions to Exercises

GRID SEARCHING Novel way of Searching 2D Array

1 if 1 x 0 1 if 0 x 1

Force on Moving Charges in a Magnetic Field

Data Structures and Algorithms

Expression. Variable Equation Polynomial Monomial Add. Area. Volume Surface Space Length Width. Probability. Chance Random Likely Possibility Odds

Graph Theory Problems and Solutions

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. Course Curriculum. DATA STRUCTURES (Code: )

Midterm Practice Problems

TREE BASIC TERMINOLOGIES

Mathematics Review for MS Finance Students

5 INTEGER LINEAR PROGRAMMING (ILP) E. Amaldi Fondamenti di R.O. Politecnico di Milano 1

PROGRESSION THROUGH CALCULATIONS FOR MULTIPLICATION

Sudoku puzzles and how to solve them

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

ML for the Working Programmer

C Programming. Charudatt Kadolkar. IIT Guwahati. C Programming p.1/34

Linear and quadratic Taylor polynomials for functions of several variables.

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:

from Recursion to Iteration

Introduction to CATIA V5

Sample Questions Csci 1112 A. Bellaachia

Introduction to Java

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

Dynamic Programming. Lecture Overview Introduction

The Fibonacci Sequence and the Golden Ratio

Figure 1: Graphical example of a mergesort 1.

Transcription:

RECURSION 1. Overview The learning objective of this lab session is to: Understand the notion of recursion, the advantages and the shortcomings of recursive functions relative to the non-recursive ones, based on some simple examples. Learn how to proper develop recursive functions 2. Brief theory reminder 2.1. The recursion mechanism An object is recursive if is defined by itself. A function is recursive if it is a self-calling function. The recursion may be: direct when in the context of a function it exist a self-call statement indirect when in the context of a function it exist a call statement to another function, that calls the first function At each function call or function self-call, the parameters and the auto variables are allocated on the stack, in an independent zone. These data have distinct values at each new self-call. The static and global variables are stored all the time in the same memory location. Consequently, any updates of their values are made only at their fixed address, so these variables conserve their values from a self-call to another. Upon return from a called function either in the main program or in the calling or self-calling function, execution continues with the next statement relative to the calling or self-calling statement. This address is also stored in the stack. Upon return, the stack rolls back to the status it was before the call or the self-call, meaning that the automatic variables and the parameters will also have their previous values. A very important thing is to stop the self-calling cycle. So, it is necessary to have an end condition, otherwise the recursive call leads to an infinite loop. In practice, it is necessary to have a finite depth of the recursion; moreover this depth must be small enough, because each recursive call requires allocations on the stack for: all the parameters of the recursive function all the automatic variables of the function the return address. That means that the stack may rapidly grow, occupying in the end the entire memory area allocated to the stack. A classic example of a recursive process is the computation of the factorial, defined as follows: 1 fact( n) n* fact( n 1) Note that in the definition of the function fact, there is a zone that is not self-definition: fact(n)=1 if n=0. This is the initialization statement. In C/C++, the corresponding program sequence is: double fact(int n) if (n==0) return 1.0; return n*fact(n-1); if if n 0 n 0 T.U. Cluj-Napoca Computer Programming 1

The linear recursion is characterized by the fact that on different branches of the program there may not appear more then one recursive call, so on each level we may have only one recursive call. The linear recursion may be transformed in iteration, saving both memory and computation time, by eliminating the context-saving operations caused by each recursive call of the function. The main advantage of the recursion resides in the possibility to write programs in a more compact end clear manner. The most often recursively designed computation processes are backtracking and divide and conquer principle based methods. 2.2. Examples 2.2.1. Reading and printing, mirrored, n words (character strings), each of them having a space at the end: /* Program L7Ex1.c */ /* The program reads and prints, mirrored, n words, separated by spaces, having a space and a newline character after the last word */ void reverse(void) char c; scanf("%c", &c); if (c!=' ') printf("%c", c); reverse(); printf("%c", c); int n, i; printf("\nthe number of the words="); scanf("%d", &n); for(i=1; i<=n; ++i) reverse(); printf("\n"); printf("\nend of the program.\n"); The function reverse reads and then prints the characters one by one, until a space is encountered. At each self-call, the local variable c is stored on the stack. When space is encountered, the cycle of the self-calls is stopped, and a space, followed by the characters written in reverse order are printed. 2.2.2. Finding the minimum of a string of n integers: /* Program L7Ex2.c */ #include <limits.h> T.U. Cluj-Napoca Computer Programming 2

/* The program computes the minimum of a array of integer numbers*/ #define NMAX 100 #define MAXIMUM INT_MAX int array[nmax]; int minim(int x, int y) if (x <= y) return x; else return y; int term_min(int arraysize) if (arraysize >= 0) return minim(array[arraysize], term_min(arraysize - 1)); else return MAXIMUM; int i, n; printf("\ninput the number of the elements of the array n="); scanf("%d",&n); printf("\ninput the values of the elements\n"); for (i=0; i<n; ++i) printf("array[%d]=", i); scanf("%d", &array[i]); printf("\ninput array:\n"); for (i=0; i<n; ++i) printf("%6d", array[i]); if ((i+1) % 10 == 0) printf("\n"); printf("\nthe minimum is %d\n", term_min(n-1)); printf("\npress a key!"); 2.2.3. The recursive and non-recursive version of the n th Fibonacci term computation. Definition of Fibonacci string: Fib(0)=0; Fib(1)=1; Fib(n)=Fib(n-1)+Fib(n-2) for n 2 /* Program L7Ex3.c */ #include <conio.h> /* Fibonacci string*/ int fib1(int n) /* RECURSIVE VERSION */ if (n==0) else if (n==1) return 1; T.U. Cluj-Napoca Computer Programming 3

else return (fib1(n-1)+fib1(n-2)); int fib2(int n) /* NON-RECURSIVE VERSION */ int i, x, y, z; if (n==0) else if (n==1) return 1; else x=1;y=0; for(i=2; i<=n; ++i) z=x; x=x+y; y=z; return x; int n; char ch; ch='y'; while ((ch=='y') (ch=='y')) printf("\ninput n="); scanf("%d",&n); printf("\nrecursive COMPUTATION: fib(%d)=%d\n",n,fib1(n)); printf("\nnon-recursive COMPUTATION: fib(%d)=%d\n",n,fib2(n)); printf("\ncontinue? [Yes=Y/y] "); ch=getchar(); The recursive call rapidly grows the stack, and thus the non-recursive implementation is preferable. 3. Lab Tasks 3.1. Analyze and execute the examples provided above. Trace the stack status for a concrete case; watch its size during the self-calling cycle, and how it decreases upon return from the recursive call. 3.2. Write a recursive and a non-recursive function to calculate the values of the Hermite polynomials H(x), defined as follows: H H H 0 1 n 1; 2x 2nH n 1( x) 2( n 1) H n2 for n 2. 3.3. The towers of Hanoi. Consider three vertical pegs A, B, C, and n disks of different diameters. Initially, all the disks are placed on peg A, in descending order of their diameters (with the biggest at the bottom and the smallest at the top). The problem is to move all the disks from peg A to peg C, using peg B as intermediary, under the following conditions: T.U. Cluj-Napoca Computer Programming 4

a) at each step you can move only one disk: the disk located at top of one of the three sticks; b) it is forbidden to put a disk of a greater diameter on a disk having a smaller diameter; c) in the end, the disks must all be on peg C in the same order they were on peg A at the beginning. 3.4. Write a recursive program that reads n words and displays them in reversed order. 3.5. Write a recursive program to generate the Cartesian product (product set, direct product, cross product) of n sets. 3.6. Write a recursive program to generate the subsets of k elements of a set A with a total number of n elements (i.e. combinations of k elements taken from a total of n elements). 3.7. Write a program to solve the problem of the eight queens: i.e. find their placement on the chess board so that they have do not have the possibility to attack each other. 3.8. Generate recursively the permutations of the set A having n elements. 3.9. You have a rod R of length m, and n component rods of lengths l1, l2,..., ln that must be cut from this rod. The aim is to get at least one component of each size, with minimum loss. 3.10. Ackermann s function is defined recursively as follows: Ack (0, n) n 1 Ack ( m,0) Ack ( m 1,1) Ack ( m, n) Ack ( m 1, Ack ( m, n 1)) Write a recursive program to compute Ackermann s function: forn N * form N form, n N * 3.12. Write a recursive program to generate the partitions of a natural number n. Example: the partitions of the number 4 are: 1, 1, 1, 1, 1, 1, 2, 1, 2, 1,1, 3, 2, 1, 1, 2, 2, 3, 1, 4. Two partitions may differ either in the value of their elements, or in the order the elements are listed. 3.13. A labyrinth is coded using a m x n matrix. The passages are represented by elements equal to 1 placed on successive positions on a row or on a column. The requirement is to display all the traces that lead to the exit of the labyrinth, starting from an initial position ( i, j ). It is forbidden to pass more than once through the same point. 3.14. A knight is placed in the upper left square on a chess board of size n x n. Display all the possible paths of the knight on the chess board, such a way that every square is reached only once. 3.15. Consider a n x m matrix, with elements decimal digits (natural numbers between 1 and 9), representing colors. A connected set associated to an element is the set of elements that may be reached from this element, by successive moves on a same row or column preserving the same color. It is to determine the size and the color of the biggest connected set. In case of multiple solutions, display them all. 3.16. There are n cubes, each of them characterized by its color and the length of the edge. Generate, with some of these cubes, a maximum height tower, under the following conditions: a) a cube is placed on another only if its edge length is less than the edge length of the cube placed bellow it. b) two neighboring cubes must have different colors. T.U. Cluj-Napoca Computer Programming 5