Presentation is loading. Please wait.

Presentation is loading. Please wait.

9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 08 Iteration and Recursion in Procedure Oriented Programming Reference:

Similar presentations


Presentation on theme: "9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 08 Iteration and Recursion in Procedure Oriented Programming Reference:"— Presentation transcript:

1 9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 08 Iteration and Recursion in Procedure Oriented Programming Reference: R.Sebesta, Section 8.3

2 9/14/2015Assoc. Prof. Stoyan Bonev2 Lecture Contents: Basic notions Syntax representation of iteration Syntax representation of recursion Comparison of iterative and recursive algorithms Examples – source texts in C/C++, Perl, Python

3 9/14/2015Assoc. Prof. Stoyan Bonev3 Instead introduction “To iterate is human, to recurse is divine.” L. Peter Deutsch

4 9/14/2015Assoc. Prof. Stoyan Bonev4 Who is L Peter Deutsch ? L Peter Deutsch (born Laurence Peter Deutsch, Aug 7, 1946,) is the creator of Ghostscript, a free software PostScript and PDF interpreter.GhostscriptPostScriptPDF Deutsch's other work includes the definitive Smalltalk implementation that, among other innovations, inspired Java just- in-time technology 15 years later. He also wrote the PDP-1 Lisp 1.5 implementation, Basic PDP-1 LISP, when he was 12–15 old.SmalltalkJavajust- in-timePDP-1Lisp 1.5Basic PDP-1 LISP Deutsch received Ph.D. in CS from the Uni California, Berkeley in 1973. In 1994 he was inducted as a Fellow of the ACM.CSUni California, BerkeleyFellow Deutsch changed his legal first name from "Laurence" to "L" on Sep 12, 2007. His published work and public references before that time generally use L. Peter Deutsch (with a dot after the L). In January 2009, after auditing undergraduate Music courses at Stanford University, he entered the postgraduate Music program at California State University, East Bay, and was awarded a M.A. in March 2011. As of mid 2011, he has had 6 compositions performed on public concerts, and now generally identifies himself as a composer rather than a software developer. Stanford UniversityCalifornia State University, East Bay

5 9/14/2015Assoc. Prof. Stoyan Bonev5 Basic notions Iteration is known as a way (approach) to express repetition or looped processing. Recursion is known as a way (approach) to describe –a function in the terms of the same function itself or –a process in the terms of the same process itself or –a data structure in the terms of the same data structure.

6 9/14/2015Assoc. Prof. Stoyan Bonev6 Iteration Iteration is the repetition of a process, typically within a computer program. It can be used both as a general term, synonymous with repetition, and to describe a specific form of repetition with a mutable state.processcomputer programmutable When used in the first sense, recursion is an example of iteration, but typically using a recursive notation, which is typically not the case for iteration.recursion However, when used in the second (more restricted) sense, iteration describes the style of programming used in imperative Programming Languages.

7 9/14/2015Assoc. Prof. Stoyan Bonev7 Iteration Here is an example of iteration, in imperative pseudocode:pseudocode var i, a := 0 // initialize a before iteration for i from 1 to 3 // loop three times { a := a + i // increment a by current value of I } print a // the number 6 is printed In this program fragment, the value of the variable i changes over time, taking the values 1, 2 and 3. This changing value—or mutable state—is characteristic of iteration.

8 9/14/2015Assoc. Prof. Stoyan Bonev8 Iteration The essence of iteration and its syntax representation is in the form of a variety of counter controlled and logically controlled loop statements. The syntax of PL offers too many ways to describe iteration. It’s a diversity of for, while, do … while and even if and goto statements being used to specify iteration.

9 9/14/2015Assoc. Prof. Stoyan Bonev9 Iteration (examples ) for (int I=1; I<=100; I++) tab[I]= I*I*I;

10 9/14/2015Assoc. Prof. Stoyan Bonev10 Iteration (examples ) for (int I=1; I<=100; I++) tab[I]= I*I*I; int I=1; while(I<101) { tab[I] = I*I*I; I++; }

11 9/14/2015Assoc. Prof. Stoyan Bonev11 Iteration (examples ) for (int I=1; I<=100; I++) tab[I]= I*I*I; int I=1; while(I<101) { tab[I] = I*I*I; I++; } int I=1; do { tab[I] = I*I*I; I++; } while (I<=100);

12 9/14/2015Assoc. Prof. Stoyan Bonev12 Recursion In MATH and COS, recursion specifies a class of objects by defining a few very simple base cases (often just one), and then defining rules to break down complex cases into simpler cases.MATHCOS For example, the following is a recursive definition of person's ancestors: One's parents are one's ancestors (base case or simple case); The parents of any ancestor are also ancestors of the person under consideration (recursion step). For instance, your ancestors are: your parents, and your parents' parents (= grandparents), and your grandparents' parents, and everyone else you get by successively adding ancestors

13 9/14/2015Assoc. Prof. Stoyan Bonev13 Recursion It is convenient to think that a recursive definition defines objects in terms of "previously defined" objects of the class to define. Definitions such as these are often found in mathematics. For example, the formal definition of natural numbers is:natural numbers 0 is a natural number, and Each natural number has a successor, which is also a natural number.

14 9/14/2015Assoc. Prof. Stoyan Bonev14 Is zero(0) a natural number? In mathematics, a natural number can mean either an element of the set {1, 2, 3,...} (i.e. the positive integers) or an element of the set {0, 1, 2, 3,...} (i.e. the non- negative integers). The former is generally used in number theory, while the latter is preferred in set theory and computer science.mathematics123positiveintegers0123non- negative number theoryset theorycomputer science Natural numbers have two main purposes: they can be used for counting ("there are 3 apples on the table"), and they can be used for ordering ("this is the 3rd largest city in the country").countingordering

15 9/14/2015Assoc. Prof. Stoyan Bonev15 Recursion To visualize recursion, it can be helpful to consider recursively-defined geometric figures, such as: the Koch curve,Koch curve the Sierpinski triangle,Sierpinski triangle the Cantor set.Cantor set

16 9/14/2015Assoc. Prof. Stoyan Bonev16 Koch curve A Koch snowflake is the union of infinitely many regions whose boundary is triangle. Each time new triangles are added (an iteration), the perimeter grows. It diverges to infinity with the number of iterations. The length of the Koch snowflake's boundary is infinite, while its area remains finiteKoch snowflake

17 9/14/2015Assoc. Prof. Stoyan Bonev17 Koch curve

18 9/14/2015Assoc. Prof. Stoyan Bonev18 Koch curve The Koch Curve is almost same as Koch Snowflake (or Koch Star), except it starts with a line segment instead of an equilateral triangle.line segment equilateral triangle One can imagine that it was created by starting with a line, then recursively altering each line segment as follows: 1.divide the line segment into three segments of equal length. 2.draw an equilateral triangle that has the middle segment from step one as its base. 3.remove the line segment that is the base of the triangle from step 2. The Koch Curve has an infinite length. The area of the Koch Snowflake is 8/5 that of the initial triangle, so an infinite perimeter encloses a finite area.

19 9/14/2015Assoc. Prof. Stoyan Bonev19 Koch curve

20 9/14/2015Assoc. Prof. Stoyan Bonev20 Sierpinsky triangle An algorithm for obtaining arbitrarily close approximations to the Sierpinski triangle is as follows: Start with any triangle in a plane. The canonical Sierpinski triangle uses an equilateral triangle with a base parallel to the horizontal axis.equilateral triangle 1.Shrink the triangle by 1/2, make three copies, and position the three copies so that each triangle touches the two other triangles at a corner, (image on next slide). 2.Repeat step 1 with each of the smaller triangles.

21 9/14/2015Assoc. Prof. Stoyan Bonev21 Sierpinsky triangle

22 9/14/2015Assoc. Prof. Stoyan Bonev22

23 9/14/2015Assoc. Prof. Stoyan Bonev23 Sierpinsky triangle Note that this infinite process is not dependent upon the starting shape being a triangle - it is just clearer that way. The first few steps starting, for example, from a square also tend towards a Sierpinski gasket.

24 9/14/2015Assoc. Prof. Stoyan Bonev24

25 9/14/2015Assoc. Prof. Stoyan Bonev25 Cantor set The Cantor set, introduced by German mathematician Georg Cantor, is a remarkable construction involving only the real numbers between zero and one.Germanmathematician Georg Cantorreal numbers The Cantor set is defined by repeatedly removing the middle thirds of line segments. One starts by removing the middle third from the unit interval [0, 1], leaving [0, 1/3] ∪ [2/3, 1]. Next, the "middle thirds" of all of the remaining intervals are removed. This process is continued ad infinitum. The Cantor set consists of all points in the interval [0, 1] that are not removed at any step in this infinite process.intervalad infinitum The first six steps of this process are illustrated below.

26 9/14/2015Assoc. Prof. Stoyan Bonev26 Cantor set

27 9/14/2015Assoc. Prof. Stoyan Bonev27 Recursion in real life Let’s imagine a person staying in a museum hall between two mirrors located one across the other. It is to be seen how an image is composed using its own components (fragments).

28 9/14/2015Assoc. Prof. Stoyan Bonev28 Recursion Also, examples of recursion abound in natural language, often appearing as, or transforming into jokes. These jokes can help one develop an intuition for recursion.jokes For example, responding to the question, "What do you mean what do I mean?" with "What do you mean 'What do you mean what do I mean?'?", can clearly go on forever, although it is unclear how many iterations can be meaningful. Studying recursion in mathematics and programming languages can help to understand the meaning and philosophy of language in this sense, and a careful observation of language in this sense can help to understand recursion.mathematicsprogramming languages

29 9/14/2015Assoc. Prof. Stoyan Bonev29 Recursion in mathematics Functional Recursion Mathematical recursion involves a function calling on itself over and over until reaching an end state (base case or simple case). Each iteration increases the depth of the call. Once the end state is achieved, the function then backs all the way out, step by step. The key points of this kind of recursion are two: 1.You have to have a function that calls itself with a smaller subset of the values with which it began. 2.The function must be aware that an end state exists which terminates the recursive process.

30 9/14/2015Assoc. Prof. Stoyan Bonev30 Recursion in computing Recursion in computer programming defines a function in terms of itself. One basic form of recursive computer program is to define one or a few base cases, and then define rules to break down other cases into the base case. This is analytic recursion. Another, similar form is generative recursion. This is synthetic recursion. In this scheme, the computer uses rules to assemble cases, and starts by selecting a base case.

31 9/14/2015Assoc. Prof. Stoyan Bonev31 Recursion The essence of recursion and its syntax representation is in the form of a subprogram call statement. Recursive function: A function that calls itself is said to be recursive. The syntax of PL offers one only way to describe recursion. It’s the mechanism of a subprogram (function, procedure) call statement. The subprogram definition assigns a name to the routine permitting multiple calls to the routine from outside (other routines) or from inside (the routine itself).

32 9/14/2015Assoc. Prof. Stoyan Bonev32 Recursive algorithms Simple case: Problem case for which a straightforward solution is known. The recursive algorithms generally consist of if statement with the following form: if ( ) ; else ; Each recursive algorithm needs a simple case. It is also called a boundary condition that is used to stop, to interrupt, to finalize or to break the recursive calls sequence.

33 9/14/2015Assoc. Prof. Stoyan Bonev33 Local Referencing Environments Local variables in recursive functions –Same names –Different memory locations –Separate ”layers”

34 9/14/2015Assoc. Prof. Stoyan Bonev34 Recursion (examples): Conditional expression after McCarthy: Notation: [ b 1 > e 1, b 2 > e 2, …, b n > e n, e n+1 ] b 1, b 2, …, b n Boolean expression(s) e 1, e 2, …, e n, e n+1 Expression(s)

35 9/14/2015Assoc. Prof. Stoyan Bonev35 Factorial The commonly used example is the function used to calculate the factorial of an integerfactorialinteger Factorial(n) = n * Factorial(n-1), iff n<>0 Factorial(0) = 1 Factorial(n) = [ (n=0) > 1, n*Factorial(n-1) ]

36 9/14/2015Assoc. Prof. Stoyan Bonev36 Greatest Common Divisor GCD(m, n) = GCD(n, m % n), iff n<>0 GCD(m, 0) = m GCD(m, n) = [ (n=0) > m, GCD(n, m%n) ]

37 9/14/2015Assoc. Prof. Stoyan Bonev37 Fibonacci series 1, 1, 2, 3, 5,... Fib(n) = Fib(n-1) + Fib(n-2), iff n>=2 Fib(0) = 1 Fib(1) = 1 Fib(n) = [ (n=0)>1, (n=1)>1, Fib(n-1)+Fib(n-2) ]

38 9/14/2015Assoc. Prof. Stoyan Bonev38 Fibonacci series 1, 1, 2, 3, 5,... Fibonacci (1170–1250) discovered the numerical series now named after him, which is closely connected to golden ratio (1.618033989).Fibonacci At least since the Renaissance, many artists and architects have proportioned their works to approximate the golden ratio—especially in the form of the golden rectangle, in which the ratio of the longer side to the shorter is the golden ratio— believing this proportion to be aesthetically pleasing.Renaissanceartists architectsgolden rectangleaesthetically http://www.answers.com/Golden%20Ratio

39 9/14/2015Assoc. Prof. Stoyan Bonev39 Classification of recursion Recursive definition (primitive recursion): A call to the function itself appears in the function’s definition body. –Example: factorial, greatest common divisor Recursive reference (referenced recursion): A call to the function itself appears as an argument in the list of parameters. –Example: double integral I 2 = I 1 (a,b,I 1 (c,d,G))

40 9/14/2015Assoc. Prof. Stoyan Bonev40 Ackerman function The Ackerman function illustrates both primitive recursion & referenced recursion. A(m,n)= n+1, iff m=0 = A(m-1, 1), iff n=0 = A(m-1, A(m, n-1)) Exercise: Define Ackerman function as a conditional expression after McCarthy

41 9/14/2015Assoc. Prof. Stoyan Bonev41 Classification of recursion Direct recursion and/or Indirect recursion Depth of a recursion – the count (number) of recursive calls for fixed argument value(s). It should be finite value. In case of infinite depth of a recursion, the algorithm should be classified as a regressive algorithm.

42 9/14/2015Assoc. Prof. Stoyan Bonev42 Classification of recursion Recursive data structures: – binary tree; – list – grammar of arithmetic expressions

43 9/14/2015Assoc. Prof. Stoyan Bonev43 Storage size/Time Performance Object code size, bytes FactorialGCD Fibonacci series Iteration407434567 Recursion387406426 Execution speed (time performance), msec Nr proc val10 00020 00030 Iteration770220<10 Recursion220038017470

44 9/14/2015Assoc. Prof. Stoyan Bonev44 Iteration vs. Recursion Iteration takes more memory space. Recursion takes more time to execute. Recursive algorithms are not transparent (bad readability). Not easy to understand. Difficult to localize errors and to debug. Recursive functions are often regarded as more elegant than alternative implementations and they are usually shorter and simpler.

45 9/14/2015Assoc. Prof. Stoyan Bonev45 Why is Fibonacci recursion so slow? Fib(n) = Fib(n-1) + Fib(n-2), iff n>=2 To evaluate Fib(n), we need 2 calls. To evaluate Fib(n-1), we need 2 more calls. To evaluate Fib(n-2), we need 2 more calls. There exists an exponential growth of recursive calls_________ 4 __________ ____3 _________2_____ ___2_____1111

46 9/14/2015Assoc. Prof. Stoyan Bonev46 Fib(n) = Fib(n-1) + Fib(n-2) nmr(n) – how many times function is called to evaluate Fib(n) n 0123456 nmr(n) 11359 1525 nmr(n) = nmr(n-1) + nmr(n-2) + 1 nmr(0) = 1 nmr(1) = 1

47 9/14/2015Assoc. Prof. Stoyan Bonev47 How to approve Fib(n) slow speed? The standard recursive version: int fibr(int n) { if (n==0 || n==1) return 1; return fibr(n-1) + fibr(n-2); }

48 9/14/2015Assoc. Prof. Stoyan Bonev48 How to approve Fib(n) slow speed? A table is created to save/collect evaluated values struct val { double value; bool filled; }; extern val tab[]; int fibr(int n) { if (n==0 || n==1) return 1; if (tab[n].filled == false) { tab[n].value = fibr(n-1) + fibr(n-2); tab[n].filled = true; } return tab[n].value; }

49 9/14/2015Assoc. Prof. Stoyan Bonev49 Statistics Fibonacci series Object code size, Time performance, bytesmsec Iteration 567 <10 Recursion 42617470 Approved Recursion 575 <10

50 9/14/2015Assoc. Prof. Stoyan Bonev50 Bad readable recursive algorithm Try to analyze and describe the algorithm: void printd(int n) { if (n<0) { putchar(‘-‘); n=-n; } if (n/10) printd(n/10); putchar(n%10 + ‘0’); }

51 9/14/2015Assoc. Prof. Stoyan Bonev51 Source texts of iterative and recursive algorithms Factorial Greatest common divisor Fibonacci series Square root Sum of natural numbers Sum of array elements F(n) and Ackerman function Function main() calling itself Simulate add, multiply, divide, power operators

52 9/14/2015Assoc. Prof. Stoyan Bonev52 Factorial in C, C++, Java, C# int facti(int n) {if (n==0 || n==1) return 1; int i, res=1; for (i=2; i<=n; i++) res *= i; return res; } int factr(int n){if (n==0 || n==1) return 1; return n * factr(n-1); }

53 9/14/2015Assoc. Prof. Stoyan Bonev53 Factorial in C #include int facti(int n); int factr(int n); void main(){ int i; printf("C Greeting Hello, World"); // Test Factoriel recursive and iterative versions for(i=0; i<=10; i++) { printf("\n%d -> %d -> %d", i, facti(i), factr(i)); } }

54 9/14/2015Assoc. Prof. Stoyan Bonev54 Factorial in C++ #include using namespace std; int facti(int n); int factr(int n); void main(){ cout <<"CPP Greeting Hello, World"; // Test Factoriel recursive and iterative versions for(int i=0;i<=10;i++) { cout " " << factr(i); }

55 9/14/2015Assoc. Prof. Stoyan Bonev55 Factorial in Java public class ProgIterationRecursion { public static void main(String args[]) { for(int i=0;i<=10;i++) System.out.println(" "+i+" "+facti(i)+" "+factr(i)); } // end of main static int facti(int n) { if (n==0 || n==1) return 1; int i, res=1; for (i=2; i<=n; i++) res *= i; return res; } static int factr(int n) { if (n==0 || n==1) return 1; return n * factr(n-1); } } // end of main class

56 9/14/2015Assoc. Prof. Stoyan Bonev56 Factorial in C# using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IterationRecursion { class Program { static void Main(string[] args) { for (int i = 0; i <= 10; i++) Console.WriteLine(" "+i+" "+facti(i)+" "+factr(i)); } // end of Main static int facti(int n) { if (n==0 || n==1) return 1; int i, res=1; for (i=2; i<=n; i++) res *= i; return res; } static int factr(int n) { if (n==0 || n==1) return 1; return n * factr(n-1); } } // end of main class Program } // end of namespace

57 9/14/2015Assoc. Prof. Stoyan Bonev57 Factorial in Perl #!/usr/bin/perl sub Facti {$Arg1 = shift(@_); if($Arg1 == 0) {return(1);} $Result = 1; for ($i=1; $i <= $Arg1; $i++) { $Result = $Result * $i; } return($Result); } sub Factr {my($Arg1) = shift(@_); if($Arg1 == 0) {return(1);} else {return($Arg1 * &Factr($Arg1-1)); } }

58 9/14/2015Assoc. Prof. Stoyan Bonev58 Factorial in Perl # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; for($k=0; $k<=10; $k++) {print "\n".$k." >> ".&Facti($k)." - ".&Factr($k);}

59 9/14/2015Assoc. Prof. Stoyan Bonev59 Factorial in Python def facti(n): i, res = 1, 1 while i <= n: res, i = res*i, i+1 return res def factr(n): if n==0:return 1 else:return n * factr(n-1)

60 9/14/2015Assoc. Prof. Stoyan Bonev60 Factorial in Python print "Python greeting Hello, world!“ listnum = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] print " " print "Factorial recursive and iterative versions" for k in listnum: print k, factr(k), facti(k)

61 9/14/2015Assoc. Prof. Stoyan Bonev61 GCD in C, C++, Java, C# int gcdi(int m, int n){if(n==0) return m; int r; while ( (r=m%n)!=0 ) { m=n; n=r; } return n; } int gcdr(int m, int n){if(n==0) return m; return gcdr(n, m%n); }

62 9/14/2015Assoc. Prof. Stoyan Bonev62 GCD in C, C++, Java, C# // version C for(i=0; i<=10; i++) printf("\n10,%d -> %d -> %d", i, gcdi(10,i), gcdr(10,i)); // version C++ for(int i=0;i<=10;i++) cout " " << gcdr(10,i); // version Java for(int i=0;i "+gcdi(10,i)+" -> "+gcdr(10,i)); // version C# for(int i=0;i<=10;i++) Console.WriteLine("10," + i + " -> " + gcdi(10, i) + " -> " + gcdr(10, i));

63 9/14/2015Assoc. Prof. Stoyan Bonev63 GCD in Perl #!/usr/bin/perl sub GCDi {$Arg1 = shift(@_); $Arg2 = shift(@_); if($Arg2 == 0) {return($Arg1);} while( ($Rem=($Arg1%$Arg2)) != 0) { $Arg1 = $Arg2; $Arg2 = $Rem; } return($Arg2); } sub GCDr {my($Arg1) = shift(@_); my($Arg2) = shift(@_); if($Arg2 == 0) {return($Arg1);} else {return(&GCDr($Arg2, $Arg1%$Arg2)); } }

64 9/14/2015Assoc. Prof. Stoyan Bonev64 GCD in Perl # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; print "\nGCD"; for($l=0; $l<=10; $l++) {print "\n10,".$l." >> ".&GCDi(10, $l)." - ".&GCDr(10, $l);}

65 9/14/2015Assoc. Prof. Stoyan Bonev65 GCD in Python def gcdi(m, n): if n==0: return m rem = m % n while rem != 0: m, n, rem = n, rem, m % n return n def gcdr(m, n): if n==0:return m else:return gcdr(n, m%n)

66 9/14/2015Assoc. Prof. Stoyan Bonev66 GCD in Python print "Python greeting Hello, world!" listnum = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] print " " print "GCD recursive and iterative versions" for k in listnum: print 10, k, gcdr(10, k), gcdi(10, k)

67 9/14/2015Assoc. Prof. Stoyan Bonev67 Sum Σi in C, C++, Java, C# int sumi(int n) // Sum of natural numbers { if (n==0 || n==1) return n; int i, sum = 0; for (i=1; i<=n; i++) sum+= i; return sum; } int sumr(int n) { if (n==0 || n==1) return n; return n + sumr(n-1); }

68 9/14/2015Assoc. Prof. Stoyan Bonev68 Sum Σi in C, C++, Java, C# // version C for(i=0; i<=10; i++) printf("\n%d -> %d -> %d", i, sumi(i), sumr(i)); // version C++ for(int i=0;i<=10;i++) cout " " << sumr(i); // version Java for(int i=0;i "+sumi(i)+" -> "+sumr(i)); // version C# for(int i=0;i<=10;i++) Console.WriteLine(" " + i + " -> " + sumi(i) + " -> " + sumr(i));

69 9/14/2015Assoc. Prof. Stoyan Bonev69 Sum Σi in Perl #!/usr/bin/perl sub sumi {$Arg1 = shift(@_); if($Arg1==0 || $Arg1==1) {return($Arg1);} $Sum = 0; for ($i=1; $i <= $Arg1 ; $i++) {$Sum += $i;} return($Sum); } sub sumr {my($Arg1) = shift(@_); if($Arg1==0 || $Arg1==1) {return($Arg1);} return($Arg1 + &sumr($Arg1-1)); }

70 9/14/2015Assoc. Prof. Stoyan Bonev70 Sum Σi in Perl # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; print "\nSum of natural numbers"; for($l=0; $l<=10; $l++) {print "\n".$l." >> ".&sumi($l)." - ".&sumr($l);}

71 9/14/2015Assoc. Prof. Stoyan Bonev71 Sum Σi in Python # Sum of natural numbers def sumi(n): if n==0:return n i, sum = 1, 0 while i <= n: sum, i = sum + i, i+1 return sum def sumr(n): if n==0:return n else:return n + sumr(n-1)

72 9/14/2015Assoc. Prof. Stoyan Bonev72 Sum Σi in Python print "Python greeting Hello, world!" listnum = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] print " " print "Sum natural numbers recursive and iterative versions" for k in listnum: print k, sumr(k), sumi(k)

73 9/14/2015Assoc. Prof. Stoyan Bonev73 Sum Σa[I] in C // Sum of 1-dimensioned array elements int ar1sumi(int b[], int n) { int i, sum=0; for (i=0; i<=n; i++) sum += b[i]; return sum; } int ar1sumr(int b[], int n) { if (n==0) return b[0]; return b[n] + ar1sumr(b, n-1); }

74 9/14/2015Assoc. Prof. Stoyan Bonev74 Sum Σa[I] in C #include // Sum of 1-dmensioned array elements int ar1sumi(int b[], int n); int ar1sumr(int b[], int n); void main() { int i; printf("C Greeting Hello, World"); // Test Sum of 1-dimensioned array elements printf("\n\nSum of 1-dimenisioned array elements\n"); int mas1[]={ 5, 10, 20, 30, 40, 50, 60}; for (i=0; i<=6; i++) printf("%d ", mas1[i]); printf(" >> %d >> %d", ar1sumi(mas1, 6), ar1sumr(mas1, 6)); }

75 9/14/2015Assoc. Prof. Stoyan Bonev75 Sum Σa[I] in C++ #include using namespace std; // Sum of 1-dmensioned array elements int ar1sumi(int b[], int n); int ar1sumr(int b[], int n); int main() { cout <<"CPP Greeting Hello, World"; // Test Sum of 1-dimensioned array elements cout <<"\n\nSum of 1-dimenisioned array elements\n"; int mas1[] = { 5, 10, 20, 30, 40, 50, 60}; for (int i=0; i<=6; i++) cout << mas1[i] << " "; cout " " << ar1sumr(mas1, 6); }

76 9/14/2015Assoc. Prof. Stoyan Bonev76 Sum Σa[I] in Perl sub ar1sumi{@ArgList = @_; $sum = 0; for ($i=0;$i<=$#ArgList;$i++) {$sum+=$ArgList[$i];} return($sum); } sub ar1sumr{my(@ArgList) = @_; my($Index)=$#ArgList; if ($Index==0) {return ($ArgList[$Index]);} return ($ArgList[0]+ar1sumr(@ArgList[1..$Index])); }

77 9/14/2015Assoc. Prof. Stoyan Bonev77 Sum Σa[I] in Perl print "\nSum of 1-dimensioned array elements "; @mas = ( 5, 10, 20, 30, 40, 50, 60 ); for ($i=0; $i<=$#mas; $i++) { print $mas[$i]." ";} print "\nIterative sum of an array/list = ".ar1sumi(@mas); print "\nRecursive sum of an array/list = ".ar1sumr(@mas); getc();

78 9/14/2015Assoc. Prof. Stoyan Bonev78 Fibonacci series in C, C++, Java, C# int fibi(int n) { int i, va=1, vb=1, vc=1; if (n==0 || n==1) return 1; for (i=2; i<=n; i++) { vc = va + vb;va = vb; vb = vc; } return vc; } int fibr(int n) { if (n==0 || n==1) return 1; return fibr(n-1) + fibr(n-2); }

79 9/14/2015Assoc. Prof. Stoyan Bonev79 Fibonacci series in C, C++, Java, C# // version C for(i=0; i<=10; i++) printf("\n%d -> %d -> %d", i, fibi(i), fibr(i)); // version C++ for(int i=0;i<=10;i++) cout " " << fibr(i); // version Java for(int i=0;i<=10;i++) System.out.println(" "+i+" -> "+fibi(i)+" -> "+fibr(i)); // version C# for(int i=0;i<=10;i++) Console.WriteLine(" " + i + " -> " + fibi(i) + " -> " + fibr(i));

80 9/14/2015Assoc. Prof. Stoyan Bonev80 Fibonacci series in Perl #!/usr/bin/perl sub fibi {$Arg1 = shift(@_); if($Arg1==0 || $Arg1==1) {return($Arg1);} $va=0; $vb=1; for ($i=2; $i <= $Arg1 ; $i++) {$vc = $va+$vb; $va = $vb; $vb = $vc;} return($vc); } sub fibr {my($Arg1) = shift(@_); if($Arg1==0 || $Arg1==1) {return($Arg1);} return( &fibr($Arg1-1) + &fibr($Arg1-2) ); }

81 9/14/2015Assoc. Prof. Stoyan Bonev81 Fibonacci series in Perl # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; print "\nFibonacci"; for($l=0; $l<=10; $l++) {print "\n".$l." >> ".&fibi($l)." - ".&fibr($l);} getc();

82 9/14/2015Assoc. Prof. Stoyan Bonev82 Fibonacci series in Python # Fibonacci series module def fibi(n):# Fibonacci series up to n va, vb, i = 0, 1, 2 while i <= n: va, vb, i = vb, va+vb, i+1 return vb def fibr(n): if n==0:return n elif n==1:return n else:return fibr(n-1) + fibr(n-2)

83 9/14/2015Assoc. Prof. Stoyan Bonev83 Fibonacci series in Python print "Python greeting Hello, world!" listnum = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] print "Fibonacci recursive and iterative versions" for k in listnum: print k, fibr(k), fibi(k) #read (ch)

84 9/14/2015Assoc. Prof. Stoyan Bonev84 Square root in C, C++, Java, C# // C,C++: abs( ) Java: Math.abs( ) C#: Math.Abs( ) double sqrti(double x, double eps) { double yn=1, yn1=(x/yn+yn)/2; while (abs(yn-yn1)>eps) {yn=yn1; yn1=(x/yn+yn)/2;} return yn; } double sqrtr(double x, double start, double eps) { if (abs(start*start-x) < eps) return start; return sqrtr(x, (start*start +x)/(2*start), eps); }

85 9/14/2015Assoc. Prof. Stoyan Bonev85 Square root in C, C++, Java, C# // version C printf("\n\nSquare root simulations"); printf("\n 25 -> %lf -> %lf", sqrti( 25,0.001), sqrtr( 25,1,0.001)); printf("\n144 -> %lf -> %lf", sqrti(144,0.001), sqrtr(144,1,0.001)); printf("\n289 -> %lf -> %lf", sqrti(289,0.001), sqrtr(289,1,0.001)); // version C++ cout " "<< sqrtr(25,1,0.001); cout " "<< sqrtr(144,1,0.001); cout " "<< sqrtr(289,1,0.001); // version Java System.out.println("25 -> "+sqrti(25,0.001) +" -> "+sqrtr(25,1,0.001)); System.out.println("144 -> "+sqrti(144,0.001)+" -> "+sqrtr(144,1,0.001)); System.out.println("289 -> "+sqrti(289,0.001)+" -> "+sqrtr(289,1,0.001)); // version C# Console.WriteLine("25 -> "+sqrti(25,0.001) +" -> "+sqrtr(25,1,0.001)); Console.WriteLine("144 -> "+sqrti(144,0.001)+" -> "+sqrtr(144,1,0.001)); Console.WriteLine("289 -> "+sqrti(289, 0.001)+" -> "+sqrtr(289, 1, 0.001));

86 9/14/2015Assoc. Prof. Stoyan Bonev86 Square root in Perl #!/usr/bin/perl sub sqrti {$Arg1 = shift(@_); $Arg2 = shift(@_); $yn=1.;$yn1=($Arg1/$yn + $yn)/2.; while( abs($yn-$yn1) > $Arg2) { $yn =$yn1; $yn1=($Arg1/$yn + $yn)/2. } return($yn); } sub sqrtr {my($Arg1) = shift(@_);my($Arg2) = shift(@_); my($Arg3) = shift(@_); if(abs($Arg2*$Arg2-$Arg1)<$Arg3) {return($Arg2);} return(&sqrtr($Arg1,($Arg2*$Arg2+$Arg1)/(2.*$Arg2),$Arg3)); }

87 9/14/2015Assoc. Prof. Stoyan Bonev87 Square root in Perl # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; print "\nSquare root simulations"; print "\n 25 >> ".&sqrti( 25,0.001)." - ".&sqrtr( 25,1.,0.001); print "\n144 >> ".&sqrti(144,0.001)." - ".&sqrtr(144,1.,0.001); print "\n289 >> ".&sqrti(289,0.001)." - ".&sqrtr(289,1.,0.001); getc();

88 9/14/2015Assoc. Prof. Stoyan Bonev88 Square root in Python # square root simulations def sqrti(x, eps): yn = 1 yn1 = (x/yn + yn)/2 while abs(yn-yn1)>eps: yn = yn1 yn1 = (x/yn+yn)/2 return yn def sqrtr(x, yn, eps): if abs(yn*yn-x)<eps:return yn else:return sqrtr(x, (yn*yn + x)/(2*yn), eps)

89 9/14/2015Assoc. Prof. Stoyan Bonev89 Square root in Python print " " print "SQRT recursive and iterative versions" listx = [ 25, 49, 81, 100, 289 ] for k in listx: print k, sqrtr(k, 1, 0.001), sqrti(k, 0.001)

90 9/14/2015Assoc. Prof. Stoyan Bonev90 Linear search – С++ // Iterative Linear Search int LinSearchIterative(int target, int table[], int size) { int k = 0; while ( k < size ) { if (target == table[k]) return k; k++; } return -1; } // Recursive linear search int LinSearchRecursive(int target, int table[], int low, int high) { if (high < low) return -1; if (target == table[high]) return high; return LinSearchRecursive(target, table, low, high-1); }

91 9/14/2015Assoc. Prof. Stoyan Bonev91 Binary search – С++ // Iterative Binary search int BinSearchIterative(int target, int table[], int size) { int low, high, mid; low = 0; high = size - 1; while ( low <= high ) { mid = (low + high) / 2; if (target == table[mid]) return mid; if (target < table[mid]) high = mid - 1; if (target > table[mid]) low = mid + 1; } return -1; }

92 9/14/2015Assoc. Prof. Stoyan Bonev92 Binary search – С++ // Recursive Binary search int BinSearchRecursive(int target, int table[], int low, int high) { if (low > high) return -1; int middle; middle = (low + high) / 2; if (target == table[middle]) return middle; if (target < table[middle]) // low half of the table { // high = middle-1; return BinSearchRecursive(target, table, low, middle-1); } if (target > table[middle]) // high half of the table { // low = middle+1; return BinSearchRecursive(target, table, middle+1, high); }

93 9/14/2015Assoc. Prof. Stoyan Bonev93 mul(*) operator in C/C++ int muli(int m, int n) { if (n==0) return 0; if (n==1) return m; int i, res=0; for (i=1; i<=n; i++) { res = res + m;} return res; } int mulr(int m, int n) { if (n==0) return 0; if (n==1) return m; return m + mulr(m, n-1); }

94 9/14/2015Assoc. Prof. Stoyan Bonev94 mul(*) operator in C #include int muli(int m, int n); int mulr(int m, int n); void main() { int k, l; printf("C Greeting Hello, World"); // Test multiplication mplemented as recursive and iterative rourtine printf("\n\nMultiplication implemented as Recursion and Iteration"); for (k=0; k<=12; k++) { printf("\n"); for (l=0; l<=12; l++) printf("\n%d,%d -> %d -> %d", k, l, muli(k,l), mulr(k,l)); } }

95 9/14/2015Assoc. Prof. Stoyan Bonev95 mul(*) operator in C++ #include using namespace std; int muli(int m, int n); int mulr(int m, int n); void main() { cout <<"CPP Greeting Hello, World"; // Test multiplication mplemented as recursive and iterative rourtine cout <<"\n\nMultiplication implemented as Recursion and Iteration"; for (int k=0; k<=12; k++) {cout <<"\n"; for (int l=0; l<=12; l++) cout " "<<mulr(k,l);} }

96 9/14/2015Assoc. Prof. Stoyan Bonev96 mul(*) operator in Perl #!/usr/bin/perl sub muli {$Arg1 = shift(@_); $Arg2 = shift(@_); if($Arg2==0){ return 0;} if($Arg2==1){ return $Arg1;} $res = 0; for ($i=1; $i<=$Arg2; $i++) { $res = $res + $Arg1; } return $res; } sub mulr {$Arg1 = shift(@_); $Arg2 = shift(@_); if($Arg2==0){ return 0;} if($Arg2==1){ return $Arg1;} return $Arg1 + &mulr($Arg1, $Arg2-1); }

97 9/14/2015Assoc. Prof. Stoyan Bonev97 mul(*) operator in Perl # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; # Test for MULTIPLICATION based on Recursion and Iteration print "\nMultiplication implemented using Recursion and Iteration"; for($k=0; $k<=12; $k++) { print "\n"; for($l=0; $l<=12; $l++) { print "\n".$k." ".$l." ".&muli($l, $k)." ".&mulr($l, $k); } getc();

98 9/14/2015Assoc. Prof. Stoyan Bonev98 mul(*) operator in Python # Recursive and iterative simulation of MULTIPLICATION def muli(m, n): if n==0:return 0 if n==1:return m res, i = 0, 1 while i<=n:res, i = res+m, i+1 return res def mulr(m, n): if n==0:return 0 if n==1:return m return m + mulr(m,n-1)

99 9/14/2015Assoc. Prof. Stoyan Bonev99 mul(*) operator in Python print "Python greeting Hello, world!" listnum = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] print " " print "Multiplication impl. using Recursion and Iteration" for k in listnum: print " " for l in listx: print k, l, mulr(k, l), muli(k, l)

100 9/14/2015Assoc. Prof. Stoyan Bonev100 Проблеми, решени само във версия Реккурсия Решение версия итерация е трудно и непрозрачно

101 9/14/2015Assoc. Prof. Stoyan Bonev101 Ackermann F. in C, C++, Java, C# // Ackerman function int acker(int m, int n) { if(m==0) return n+1; if(n==0) return acker(m-1,1); return acker(m-1, acker(m,n-1)); }

102 9/14/2015Assoc. Prof. Stoyan Bonev102 Ackermann F. in C, C++, Java, C# // version C printf("\nAckerman Arguments 1,1 > %d", acker(1,1)); printf("\nAckerman Arguments 2,1 > %d", acker(2,1)); printf("\nAckerman Arguments 0,51 > %d", acker(0,51)); // version C++ cout " << acker(1,1); cout " << acker(2,1); cout " << acker(0,51); // version Java System.out.println("Ackerman Arguments 1,1 > " + acker(1,1)); System.out.println("Ackerman Arguments 2,1 > " + acker(2,1)); System.out.println("Ackerman Arguments 0,51 > " + acker(0,51)); // version C# Console.WriteLine("Ackerman Arguments 1,1 > " + acker(1,1)); Console.WriteLine("Ackerman Arguments 2,1 > " + acker(2,1)); Console.WriteLine("Ackerman Arguments 0,51 > " + acker(0, 51));

103 9/14/2015Assoc. Prof. Stoyan Bonev103 Ackermann F. in Perl #!/usr/bin/perl sub acker {my($Arg1) = shift(@_); my($Arg2) = shift(@_); if($Arg1==0) {return($Arg2 + 1);} if($Arg2==0) {return(&acker($Arg1-1, 1));} return(&acker($Arg1-1, &acker($Arg1, $Arg2-1))); } # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; print "\nAckerman function acker(m,n)"; print "\nAckerman Arguments 0,0 > ".&acker(0,0); print "\nAckerman Arguments 1,1 > ".&acker(1,1); print "\nAckerman Arguments 2,1 > ".&acker(2,1); print "\nAckerman Arguments 0,51 > ".&acker(0,51); getc();

104 9/14/2015Assoc. Prof. Stoyan Bonev104 Ackermann F. in Python # Ackerman function def acker(m, n): if m==0:return n+1 if n==0:return acker(m-1, 1) else:return acker(m-1, acker(m, n-1)) print "Python greeting Hello, world!" print " " print "Ackerman function recursive version" print acker(0, 0), acker(1, 1), acker(2, 1), acker(0,51)

105 9/14/2015Assoc. Prof. Stoyan Bonev105 Hanoi towers in C // Hanoi Towers game void trantower(int ndsks, int fromndl, int tondl, int wrkndl) { if (ndsks > 0) { trantower(ndsks-1, fromndl, wrkndl, tondl); printf("\n%2d >> %2d", fromndl, tondl); trantower(ndsks-1, wrkndl, tondl, fromndl); }

106 9/14/2015Assoc. Prof. Stoyan Bonev106 Hanoi towers in C #include void trantower(int ndsks, int fromndl, int tondl, int wrkndl); void main() { printf("C Greeting Hello, World"); // Test Hanoi Towers game recursive version printf("\n\nHanoi towers game - 1 disk"); trantower(1, 1, 3, 2); printf("\n\nHanoi towers game - 2 disks"); trantower(2, 1, 3, 2); printf("\n\nHanoi towers game - 3 disks"); trantower(3, 1, 3, 2); }

107 9/14/2015Assoc. Prof. Stoyan Bonev107 Hanoi towers in C++ #include using namespace std; void trantower(int ndsks, int fromndl, int tondl, int wrkndl); int main() { cout <<"CPP Greeting Hello, World"; // Test Hanoi Towers game recursive version cout <<"\n\nHanoi towers game - 1 disk"; trantower(1, 1, 3, 2); cout <<"\n\nHanoi towers game - 2 disks"; trantower(2, 1, 3, 2); cout <<"\n\nHanoi towers game - 3 disks"; trantower(3, 1, 3, 2); }

108 9/14/2015Assoc. Prof. Stoyan Bonev108 Hanoi towers in Perl #!/usr/bin/perl sub trantower{my($Arg1) = shift(@_);my($Arg2) = shift(@_); my($Arg3) = shift(@_); my($Arg4) = shift(@_); if($Arg1 >= 1) { trantower($Arg1-1,$Arg2,$Arg4,$Arg3); print "\n".$Arg2." >> ".$Arg3; trantower($Arg1-1,$Arg4,$Arg3,$Arg2); } # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; print "\n\nHanoi towers game - 1 disk "; &trantower(1, 1, 3, 2); print "\n\nHanoi towers game - 2 disks"; &trantower(2, 1, 3, 2); print "\n\nHanoi towers game - 3 disks"; &trantower(3, 1, 3, 2); getc();

109 9/14/2015Assoc. Prof. Stoyan Bonev109 Hanoi towers in Python # Hanoi towers game def trantower(ndsks, fromndl, tondl, wrkndl): if ndsks>=1: trantower(ndsks-1, fromndl, wrkndl, tondl) print fromndl, " >> ", tondl trantower(ndsks-1, wrkndl, tondl, fromndl) print "Python greeting Hello, world!" print " " print "Hanoi towers game - recursive function implemented" trantower(1, 1, 3, 2) print" " trantower(2, 1, 3, 2) print" " trantower(3, 1, 3, 2)

110 9/14/2015Assoc. Prof. Stoyan Bonev110 itoa() simulated in C // C/C++ itoa run time function simulated void printd(int n) { if (n<0) { putchar('-'); n = -n;} if(n/10 != 0) printd(n/10); putchar(n%10+'0'); }

111 9/14/2015Assoc. Prof. Stoyan Bonev111 itoa() simulated in C #include void printd(int n); void main() { printf("C Greeting Hello, World"); // Test C/C++ itoa run time function recursive version printf("\n\nC/C++ itoa run time library function"); printf("\n"); printd(123); printf("\n"); printd(-86); }

112 9/14/2015Assoc. Prof. Stoyan Bonev112 itoa() simulated in C++ // C/C++ itoa run time function simulated void printd(int n) { if (n<0) { cout << "-"; n = -n;} if(n/10 != 0) printd(n/10); cout << n%10; }

113 9/14/2015Assoc. Prof. Stoyan Bonev113 itoa() simulated in C++ #include using namespace std; void printd(int n); int main() { cout <<"CPP Greeting Hello, World"; // Test C/C++ itoa run time function recursive version cout <<"\n\nC/C++ itoa run time library function"; cout << "\n"; printd(123); cout << "\n"; printd(-86); }

114 9/14/2015Assoc. Prof. Stoyan Bonev114 itoa() simulated in Perl #!/usr/bin/perl sub printd {my($Arg1) = shift(@_); if($Arg1<0){ print"-"; $Arg1 = -$Arg1; } if( ($Arg1/10) != 0) { &printd($Arg1/10); } if ($Arg1%10 != 0) {print chr($Arg1%10 + 48);} } # start main program untitled unstructured print "\nPerl greeting: Hello, world!\n"; print "\nC/C++ itoa run time library function"; print "\n"; &printd(123); print "\n"; &printd(-86); print "\n"; &printd(5); getc();

115 9/14/2015Assoc. Prof. Stoyan Bonev115 itoa() simulated in Python # C/C++ run-time function itoa recursively simulated def printd(n): if n<0:print"-", if n<0:n = -n if n/10!=0:printd(n/10) print n%10, print "Python greeting Hello, world!" print " " print "The itoa run-time function recursively implemented as printd" printd(123) print " " printd(-567890) print " " printd(86)

116 9/14/2015Assoc. Prof. Stoyan Bonev116 Recursive traverse of directory Every folder/directory contains two types of structures: files subfolders Problem: to traverse a folder and extract names of all files and subfolders contained in a specified folder as a root – starting initial argument Java solution: Based on File class and methods isDirectory() isFile() listFiles()

117 9/14/2015Assoc. Prof. Stoyan Bonev117 Recursive traverse of directory Call: File fil = new File(“F:\\SBant”); DirFilTraverse(fil); Definition: static void DirFilTraverse(File fl) { if ( fl.isDirectory() ) { System.out.println(" Directory:"+fl.toString()); File[] files = fl.listFiles(); for (int i=0; i<files.length; i++) DirFilTraverse(files[i]); } else if ( fl.isFile() ) System.out.println(" File:"+fl.toString()); else System.out.println(" No file, no directory"); }

118 9/14/2015Assoc. Prof. Stoyan Bonev118 Exercise on lecture See handout for details More recursive problems: –Java, Malik, chapter 13, pp 823-847 –Y.Daniel Liang, chapter 20, pp 702

119 9/14/2015Assoc. Prof. Stoyan Bonev119 Recursive humour A joke is the following "definition" of recursion. –Recursion See "Recursion".Recursion This is a parody on references in dictionaries, which in some careless cases may lead to circular definitions. Every joke has element of wisdom, and also an element of misunderstanding. This is an example of an erroneous recursive definition of an object, the error being the absence of the termination condition (or lack of the initial state, if to look at it from an opposite point of view).circular definitions termination

120 ISBN 0-321-49362-1 Chapter 8 Statement-Level Control Structures

121 Copyright © 2009 Addison-Wesley. All rights reserved.1-121Copyright © 2009 Addison-Wesley. All rights reserved.1-121 Chapter 8 Topics Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions

122 Copyright © 2009 Addison-Wesley. All rights reserved.1-122Copyright © 2009 Addison-Wesley. All rights reserved.1-122 Iterative Statements The repeated execution of a statement or compound statement is accomplished either by iteration or recursion General design issues for iteration control statements: 1. How is iteration controlled? 2. Where is the control mechanism in the loop?

123 Copyright © 2009 Addison-Wesley. All rights reserved.1-123Copyright © 2009 Addison-Wesley. All rights reserved.1-123 Counter-Controlled Loops A counting iterative statement has a loop variable, and a means of specifying the initial and terminal, and stepsize values Design Issues: 1.What are the type and scope of the loop variable? 2.Should it be legal for the loop variable or loop parameters to be changed in the loop body, and if so, does the change affect loop control? 3.Should the loop parameters be evaluated only once, or once for every iteration?

124 Copyright © 2009 Addison-Wesley. All rights reserved.1-124Copyright © 2009 Addison-Wesley. All rights reserved.1-124 Iterative Statements: Examples FORTRAN 95 syntax DO label var = start, finish [, stepsize ] Stepsize can be any value but zero Parameters can be expressions Design choices: 1. Loop variable must be INTEGER 2. The loop variable cannot be changed in the loop, but the parameters can; because they are evaluated only once, it does not affect loop control 3. Loop parameters are evaluated only once

125 Copyright © 2009 Addison-Wesley. All rights reserved.1-125Copyright © 2009 Addison-Wesley. All rights reserved.1-125 Iterative Statements: Examples FORTRAN 95 : a second form: [name:] Do variable = initial, terminal [,stepsize] … End Do [name] - Cannot branch into either of Fortran’s Do statements

126 Copyright © 2009 Addison-Wesley. All rights reserved.1-126Copyright © 2009 Addison-Wesley. All rights reserved.1-126 Iterative Statements: Examples Ada for var in [reverse] discrete_range loop... end loop Design choices: - Type of the loop variable is that of the discrete range (A discrete range is a sub-range of an integer or enumeration type). - Loop variable does not exist outside the loop - The loop variable cannot be changed in the loop, but the discrete range can; it does not affect loop control - The discrete range is evaluated just once Cannot branch into the loop body

127 Copyright © 2009 Addison-Wesley. All rights reserved.1-127Copyright © 2009 Addison-Wesley. All rights reserved.1-127 Iterative Statements: Examples C-based languages for ([expr_1] ; [expr_2] ; [expr_3]) statement - The expressions can be whole statements, or even statement sequences, with the statements separated by commas –The value of a multiple-statement expression is the value of the last statement in the expression –If the second expression is absent, it is an infinite loop Design choices: - There is no explicit loop variable - Everything can be changed in the loop - The first expression is evaluated once, but the other two are evaluated with each iteration

128 Copyright © 2009 Addison-Wesley. All rights reserved.1-128Copyright © 2009 Addison-Wesley. All rights reserved.1-128 Iterative Statements: Examples C++ differs from C in two ways: 1.The control expression can also be Boolean 2.The initial expression can include variable definitions (scope is from the definition to the end of the loop body) Java and C# –Differs from C++ in that the control expression must be Boolean

129 Copyright © 2009 Addison-Wesley. All rights reserved.1-129Copyright © 2009 Addison-Wesley. All rights reserved.1-129 Iterative Statements: Examples Python for loop_variable in object : - loop body [ else: - else clause] – The object is often a range, which is either a list of values in brackets ([2, 4, 6]), or a call to the range function (range(5), which returns 0, 1, 2, 3, 4 – The loop variable takes on the values specified in the given range, one for each iteration – The else clause, which is optional, is executed if the loop terminates normally

130 Copyright © 2009 Addison-Wesley. All rights reserved.1-130Copyright © 2009 Addison-Wesley. All rights reserved.1-130 Iterative Statements: Logically- Controlled Loops Repetition control is based on a Boolean expression Design issues: –Pretest or posttest? –Should the logically controlled loop be a special case of the counting loop statement or a separate statement?

131 Copyright © 2009 Addison-Wesley. All rights reserved.1-131Copyright © 2009 Addison-Wesley. All rights reserved.1-131 Iterative Statements: Logically- Controlled Loops: Examples C and C++ have both pretest and posttest forms, in which the control expression can be arithmetic: while (ctrl_expr)do loop body while (ctrl_expr) Java is like C and C++, except the control expression must be Boolean (and the body can only be entered at the beginning -- Java has no goto

132 Copyright © 2009 Addison-Wesley. All rights reserved.1-132Copyright © 2009 Addison-Wesley. All rights reserved.1-132 Iterative Statements: Logically- Controlled Loops: Examples Ada has a pretest version, but no posttest FORTRAN 95 has neither Perl and Ruby have two pretest logical loops, while and until. Perl also has two posttest loops

133 Copyright © 2009 Addison-Wesley. All rights reserved.1-133Copyright © 2009 Addison-Wesley. All rights reserved.1-133 Iterative Statements: User-Located Loop Control Mechanisms Sometimes it is convenient for the programmers to decide a location for loop control (other than top or bottom of the loop) Simple design for single loops (e.g., break ) Design issues for nested loops 1.Should the conditional be part of the exit? 2.Should control be transferable out of more than one loop?

134 Copyright © 2009 Addison-Wesley. All rights reserved.1-134Copyright © 2009 Addison-Wesley. All rights reserved.1-134 Iterative Statements: User-Located Loop Control Mechanisms break and continue C, C++, Python, Ruby, and C# have unconditional unlabeled exits ( break ) Java and Perl have unconditional labeled exits ( break in Java, last in Perl) C, C++, and Python have an unlabeled control statement, continue, that skips the remainder of the current iteration, but does not exit the loop Java and Perl have labeled versions of continue

135 Copyright © 2009 Addison-Wesley. All rights reserved.1-135Copyright © 2009 Addison-Wesley. All rights reserved.1-135 Iterative Statements: Iteration Based on Data Structures Number of elements of in a data structure control loop iteration Control mechanism is a call to an iterator function that returns the next element in some chosen order, if there is one; else loop is terminate C's for can be used to build a user-defined iterator: for (p=root; p==NULL; traverse(p)){ }

136 Copyright © 2009 Addison-Wesley. All rights reserved.1-136Copyright © 2009 Addison-Wesley. All rights reserved.1-136 Iterative Statements: Iteration Based on Data Structures (continued) PHP - current points at one element of the array - next moves current to the next element - reset moves current to the first element Java - For any collection that implements the Iterator interface - next moves the pointer into the collection - hasNext is a predicate - remove deletes an element Perl has a built-in iterator for arrays and hashes, foreach

137 Copyright © 2009 Addison-Wesley. All rights reserved.1-137Copyright © 2009 Addison-Wesley. All rights reserved.1-137 Iterative Statements: Iteration Based on Data Structures (continued) Java 5.0 (uses for, although it is called foreach ) - For arrays and any other class that implements Iterable interface, e.g., ArrayList for (String myElement : myList) { … } C#’s foreach statement iterates on the elements of arrays and other collections: Strings[] = strList = {"Bob", "Carol", "Ted"}; foreach (Strings name in strList) Console.WriteLine ("Name: {0}", name); - The notation {0} indicates the position in the string to be displayed

138 Copyright © 2009 Addison-Wesley. All rights reserved.1-138 Iterative Statements: Iteration Based on Data Structures (continued) Lua –Lua has two forms of its iterative statement, one like Fortran’s Do, and a more general form: for variable_1 [, variable_2] in iterator ( table ) do … end –The most commonly used iterators are pairs and ipairs Copyright © 2009 Addison-Wesley. All rights reserved.1-138

139 Thank You For Your attention


Download ppt "9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 08 Iteration and Recursion in Procedure Oriented Programming Reference:"

Similar presentations


Ads by Google