SlideShare a Scribd company logo
1A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Frank NIELSEN
nielsen@lix.polytechnique.fr
A Concise and
Practical
Introduction to
Programming
Algorithms in Java
Chapter 3: Functions and recursivity
2A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
So far... Executive review
Lecture 1: Java=Typed compiled programming language
Variables: Type var; (boolean, int, long, float, double)
Assignment: var=Expression; (with type checking)
Expression: Operand1 Operator Operand2 (+-*/%)
Instruction (;) & comments // or /* */
3A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
So far... Executive review
Lecture 2: Program workflow (blocks/branching/loops)
Determine the set of instructions at runtime
Blocks: sequence of instructions { }
Branching condition: if predicate B1 else B2
(switch case break)
Loops: while, do, for and escaping break
Numerical precisions: finite-precision arithmetic
(absurd results, loose of associativity, etc.)
4A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Meaning of a function in mathematics ?
● Source (X) and target (Y) domains
● A map that associates to elements of X elements of Y
● An element of X is associated at most once to a member of Y
● The mapping gives always the same result (deterministic/no randomness)
● Functions of several variables may be built blockwise...
...using Cartesian product of spaces
5A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Meaning of functions for computing ?
● A portion of a program processing data and returning a result
●A function not returning a result is also called a procedure
●A function has typed parameters as arguments
●A function usually yields the same result for a given set of arguments
(except for side-effects or use of pseudo-randomness)
●
A function needs to be declared first before calling it elsewhere
TypeF F(Type1 arg1, Type2 arg2, ..., TypeN argN)
{
TypeF result;
block of instructions;
return result;
}
6A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
class INF311{
public static typeF F(type1 arg1, ..., typeN argN)
{
// Description
Block of instructions;
}
...
}
● This kind of function is also called a static method
● Functions must be defined inside classes
● A function not returning a result has type void
(also known as a procedure)
Declaring functions in Java
7A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Defining the body of a function in Java
Class INF311{
public static typeF F(type1 arg1, ..., typeN argN)
{
// Description
Block of instructions;
}
}
Body of a function
● Body should contain an instruction return to indicate the result
● If branching structures are used (if or switch) , a return should be
written for all different branches. Otherwise we get acompiler error!
8A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Defining the body of a function in Java
class INF311{
public static typeF F(type1 arg1, ..., typeN argN)
{
// Description
Block of instructions;
}
}
Body of a function
Body should contain an instruction return to indicate the result
If branching structures are used (if or switch) ,
then a return should be written for all different branches.
... Otherwise we get a compiler error! (why? => not type safe!)
9A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Using functions in Java
10A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
A few examples of basic functions
class FuncDecl{
public static int square(int x)
{return x*x;}
public static boolean isOdd(int p)
{if ((p%2)==0) return false;
else return true;}
public static double distance(double x, double y)
{if (x>y) return x-y;
else return y-x;}
public static void display(double x, double y)
{System.out.println("("+x+","+y+")");
return; // return void
}
public static void main (String[] args)
{
...
}
}
11A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
class FuncDecl{
public static int square(int x){...}
public static boolean isOdd(int p) {...}
public static double distance(double x, double y) {...}
public static void display(double x, double y) {...}
public static void main (String[] args)
{
display(3,2);
display(square(2),distance(5,9));
int p=123124345;
if (isOdd(p))
System.out.println("p is odd");
else System.out.println("p is even");
}
}
A few examples of basic functions
12A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions... JCreator IDE
13A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
● Modularity (ease of presentation)
● Code re-use (program once, re-use many times!)
-> library (API)
● Ease certification of correctness and test routines.
Benefits of using functions
14A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions with branching structures
ERROR!!!
This compiled but there is
an error (break keyword?!)
15A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Functions with branching structures
(correct program)
16A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Factorial function n! in Java
Call function factorial in class « toolbox »
17A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Calling functions: Inner Mechanism
TypeF result=F(param1, param2, ..., paramN);
param1, ..., paramN should be of the same types as the ones declared in the function
A function call can be used inside an expression,
or even as a parameter of another function (nested calls)
Example: F1(F2(x),F3(x))
Assignment's rule checks at compile time for type equivalence:
System.out.println(IsPrime(23121971));
double dist=distance(u,v);
Beyond the scope of the function's class, we need to put the
function' class with a dot. Requires the function to be public.
Math.cos(x);
TD2.factorial(n);
TC.lireInt();
18A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Revisiting IsPrime: measuring time
We repeat this computation
1000 times to measure
the elapsed time
Function call in class TC:
TC.demarrerChrono();
Function call in class TC:
TC.tempsChrono();
19A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Potential side effects of functions:
Static variables (effet de bord)
● Function that might modify/alterate the environment
For example:
... displaying a value
... But also modify a variable of the base class
● A class variable is declared inside the class scope,
...not in function bodies
● Class variables are declared using the keyword static
20A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Side effects of functions: Static variables
CountingCounting
number ofnumber of
function callsfunction calls
Declaration of class variable
static int classvar;
21A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Function: Signature and overloading
signature of a function = ordered sequence of parameter types
Two functions with different signatures can bear the same name
(since the compiler can distinguish them!)
static double plusone(...)
int
double
String
22A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Although the function result type is important,
Java does not take into account it for creating signatures...
Function: Signature and overloading
23A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Function: Signature and overloading
static int plusone (int n)
static double plusone(int n)
!!! COMPILATION ERROR !!!
class SignatureError{
public static int plusone(int n)
{return n+1;}
public static double plusone(int n)
{return n+1.0;}
public static void main(String args[])
{} }
C:JSignature.java:6: plusone(int) is already defined in SignatureError
static double plusone(int n)
24A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Executing functions in Java
● Work place of the function is created when the function is called
● ... and destroyed once it is executed (value returned)
● Parameter values are equal to the results of the expressions
● Function parameters are allocated in memory reserved for the function
● If a parameter is modified inside the function body,
it remains unchanged in the calling function.
public static void main(String args[])
25A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Executing functions in Java
Memory
(stack)
Memory
for main
Memory
for Increment
Memory
for plusone
As soon as we exit this
function, k takes its original
value of (5)
passage par valeur
26A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Executing functions in Java
(In C++, swapping is easy)
27A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Principle of recursion
A beautiful principle of computing !
Loosely speaking, ...
...the inverse of inductivism in mathematics
● A function that calls itself...
● ...not forever, so that there should be stopping states...
● ...Function parameters should tend to the ones that do not
...require recursion to finalize the computation...
But all this is an informal glimpse of recursion (self-structure)
28A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Example: Revisiting the factorial
29A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Population growth:
Newly born pair of M/F rabbits are put in a field.
Newly born rabbits take a month to become mature, after which time
... They produce a new pair of baby rabbits every month
Q.: How many pairs will there be in subsequent years?
Example: Fibonacci numbers
Leonard de Pise
(1170- 1245)
1, 1, 2, 3, 5, 8, 13, 21, 34, 55......
30A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Example: Fibonacci numbers
Leonard de Pise
Much better algorithms at....
http://fr.wikipedia.org/wiki/Suite_de_Fibonacci
31A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Understanding a recursive function
recursive function called:
● Allocation of memory for local variables
● Stack operations to compute
● ... Call the function with other parameters, if required
● Process operations that remains on the stack
int fibo(int n)
{int x,y;
if(n <= 1) return 1;
x=fibo(n-1);
y=fibo(n-2);
return x+y;}
x=fibo(2)
y=fibo(1)
return x+y
fibo(3)
Recursive calls
32A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
x=fibo(2)
y=fibo(1)
return x+y
x=fibo(1)
y=fibo(0)
return x+y
return 1;
fibo(3)
fibo(2)
fibo(1)
Understanding a recursive function
33A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
x=fibo(2)
y=fibo(1)
return x+y
x=1
y=fibo(0)
return x+y
return 0;
fibo(3)
fibo(2)
fibo(0)
Understanding a recursive function
34A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
x=fibo(2)
y=fibo(1)
return x+y
x=1
y=0
return x+yfibo(3)
fibo(2)=1
Understanding a recursive function
35A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
x=1
y=fibo(1)
return x+y
fibo(3) fibo(1)=1 return 1;
Understanding a recursive function
36A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
x=1
y=1
return x+y
fibo(3)=2
As we can see, there is a lot of redundant work here.
-> Very inefficient algorithm.
Can cause stack overflow if the #recursive calls...
...become too large
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, ..
Understanding a recursive function
37A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Understanding a recursive function
38A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Recursion: Halting problem
When does a recursive program terminate?
The arguments always decrease and
there is always a stopping criterion
39A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Recursion: Halting problem
40A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Does not always halt because
we may never reach terminal case (n=0) for odd numbers
Recursion: Halting problem
Do we always reach
that terminal state?
41A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
What do you think of this one?
Stack overflow
Recursion: Halting problem
42A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Syracuse problem and termination conjecture
Conjectured to halt
(computer simulation helps intuition but does not give a full proof)
Recursion: Halting problem
43A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
There is provably no algorithm that can take as input a
program (binary string) and return true
if and only if this program halts.
http://en.wikipedia.org/wiki/Halting_problem
Halting problem: Computer Science
Proof skipped
44A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Terminal recursion
Does not put function calls on the stack
(thus avoid stack overflow)
What happens if we call Factorial(100) ?
Recursive calls are alwaysof the form return f(...);
->No instruction (computation) after the function
(Factorial is not terminal since return n*f(n-1); )
if (n<=1) return 1; else
return n*f(n-1);
45A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
factorial with terminal recursion
Arguments plays the role of accumulators
What happens if we call Factorial(100) ?
46A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Terminal Recursion:
Revisiting Fibonacci
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, ...
accum
ulator
47A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Recursivity and Nature
Drawing fractal curves and motifs
Koch's snowflake
Fractals:
● Patterns that are present at different scales
● The curve at stage n is defined recursively...
....from the curve at stage n-1
48A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Fractal: Sierpinski motif
Generation 1 Generation 2 Generation 3 Generation 4 Generation 5
The recursive pattern is given by a simple rewritting rule:
Replace a triangle by 3 triangles defined by the...
midpoints of the edges of the source triangle
Waclaw Sierpinski
(1882-1969)
Polish mathematician
49A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
Sierpinski curve (2D pyramid)
http://www.enseignement.polytechnique.fr/profs/informatique/Philippe.Chassignet/MACLIB/Java/maclib_java.html
50A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
51A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen

More Related Content

What's hot

C# programs
C# programsC# programs
C# programs
Syed Mustafa
 
Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C Language
Jenish Bhavsar
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Automatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSELAutomatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSEL
Joel Falcou
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
newmedio
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scala
Amuhinda Hungai
 
Intro to Functional Reactive Programming In Scala
Intro to Functional Reactive Programming In ScalaIntro to Functional Reactive Programming In Scala
Intro to Functional Reactive Programming In Scala
Diego Alonso
 
Unit iv functions
Unit  iv functionsUnit  iv functions
Unit iv functions
indra Kishor
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
rajni kaushal
 
Kotlin
KotlinKotlin
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
Harsh Pathak
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Data Structure with C
Data Structure with CData Structure with C
Data Structure with C
Syed Mustafa
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
Zsolt Mészárovics
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
farhan amjad
 
User defined functions
User defined functionsUser defined functions
User defined functions
Rokonuzzaman Rony
 
The what over the how (another way on android development with kotlin)
The what over the how (another way on android development with kotlin)The what over the how (another way on android development with kotlin)
The what over the how (another way on android development with kotlin)
Jose Manuel Pereira Garcia
 

What's hot (20)

C# programs
C# programsC# programs
C# programs
 
Storage classes arrays & functions in C Language
Storage classes arrays & functions in C LanguageStorage classes arrays & functions in C Language
Storage classes arrays & functions in C Language
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Automatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSELAutomatic Task-based Code Generation for High Performance DSEL
Automatic Task-based Code Generation for High Performance DSEL
 
Introduction To Functional Programming
Introduction To Functional ProgrammingIntroduction To Functional Programming
Introduction To Functional Programming
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scala
 
Intro to Functional Reactive Programming In Scala
Intro to Functional Reactive Programming In ScalaIntro to Functional Reactive Programming In Scala
Intro to Functional Reactive Programming In Scala
 
Unit iv functions
Unit  iv functionsUnit  iv functions
Unit iv functions
 
Java programming lab assignments
Java programming lab assignments Java programming lab assignments
Java programming lab assignments
 
Kotlin
KotlinKotlin
Kotlin
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Data Structure with C
Data Structure with CData Structure with C
Data Structure with C
 
Ankara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with ScalaAnkara Jug - Practical Functional Programming with Scala
Ankara Jug - Practical Functional Programming with Scala
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
The what over the how (another way on android development with kotlin)
The what over the how (another way on android development with kotlin)The what over the how (another way on android development with kotlin)
The what over the how (another way on android development with kotlin)
 

Viewers also liked

(slides 4) Visual Computing: Geometry, Graphics, and Vision
(slides 4) Visual Computing: Geometry, Graphics, and Vision(slides 4) Visual Computing: Geometry, Graphics, and Vision
(slides 4) Visual Computing: Geometry, Graphics, and Vision
Frank Nielsen
 
FINEVu CR-2i english manual - www.bilkamera.se
FINEVu CR-2i english manual - www.bilkamera.seFINEVu CR-2i english manual - www.bilkamera.se
FINEVu CR-2i english manual - www.bilkamera.se
Bilkamera
 
091
091091
091
tamma07
 
2013 6-6 a difference is a source of creation
2013 6-6 a difference is a source of creation2013 6-6 a difference is a source of creation
2013 6-6 a difference is a source of creation
SUGAWARA, Hideyuki
 
Athletic Code Roundtable
Athletic Code RoundtableAthletic Code Roundtable
Athletic Code Roundtable
Jena Graham
 
Information-Geometric Lenses for Multiple Foci + Contexts Interfaces
Information-Geometric Lenses for Multiple Foci + Contexts InterfacesInformation-Geometric Lenses for Multiple Foci + Contexts Interfaces
Information-Geometric Lenses for Multiple Foci + Contexts Interfaces
Frank Nielsen
 
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Projecting Computer Graphics on Moving Surfaces: A Simple Calibration and Tr...
Projecting Computer Graphics on Moving Surfaces: A Simple  Calibration and Tr...Projecting Computer Graphics on Moving Surfaces: A Simple  Calibration and Tr...
Projecting Computer Graphics on Moving Surfaces: A Simple Calibration and Tr...
Frank Nielsen
 
Unit 4 home work
Unit 4 home workUnit 4 home work
Unit 4 home work
tamma07
 
(ISIA 3) Cours d'algorithmique (1995)
(ISIA 3) Cours d'algorithmique (1995)(ISIA 3) Cours d'algorithmique (1995)
(ISIA 3) Cours d'algorithmique (1995)
Frank Nielsen
 
THE IMPLEMENTATION OF COOPERATIVE LEARNING BY GIVING INITIAL KNOWLEDGE IN COL...
THE IMPLEMENTATION OF COOPERATIVE LEARNING BY GIVING INITIAL KNOWLEDGE IN COL...THE IMPLEMENTATION OF COOPERATIVE LEARNING BY GIVING INITIAL KNOWLEDGE IN COL...
THE IMPLEMENTATION OF COOPERATIVE LEARNING BY GIVING INITIAL KNOWLEDGE IN COL...
susilosudarman42
 
HOW TO CRACK IIT--BEST PROGRAMMES OF SRICHAITANYA:DRK RAO 9502 707070
HOW TO CRACK IIT--BEST PROGRAMMES OF SRICHAITANYA:DRK RAO 9502 707070HOW TO CRACK IIT--BEST PROGRAMMES OF SRICHAITANYA:DRK RAO 9502 707070
HOW TO CRACK IIT--BEST PROGRAMMES OF SRICHAITANYA:DRK RAO 9502 707070
D R K RAO
 
Potential Genre 2
Potential Genre 2Potential Genre 2
Potential Genre 2
idil moali
 
A new implementation of k-MLE for mixture modelling of Wishart distributions
A new implementation of k-MLE for mixture modelling of Wishart distributionsA new implementation of k-MLE for mixture modelling of Wishart distributions
A new implementation of k-MLE for mixture modelling of Wishart distributions
Frank Nielsen
 
Layne Droz Video Game
Layne Droz Video GameLayne Droz Video Game
Layne Droz Video Game
Michael Droz
 
Subjects to Consider When Developing Codes of Conduct
Subjects to Consider When Developing Codes of Conduct Subjects to Consider When Developing Codes of Conduct
Subjects to Consider When Developing Codes of Conduct
Jena Graham
 
Audience research results and conclusions
Audience research  results and conclusionsAudience research  results and conclusions
Audience research results and conclusions
gryall97
 
Gurumurthy Kalyanaram on Interpretation of Collective Bargaining Agreement (CBA)
Gurumurthy Kalyanaram on Interpretation of Collective Bargaining Agreement (CBA)Gurumurthy Kalyanaram on Interpretation of Collective Bargaining Agreement (CBA)
Gurumurthy Kalyanaram on Interpretation of Collective Bargaining Agreement (CBA)
Gurumurthy Kalyanaram
 

Viewers also liked (18)

(slides 4) Visual Computing: Geometry, Graphics, and Vision
(slides 4) Visual Computing: Geometry, Graphics, and Vision(slides 4) Visual Computing: Geometry, Graphics, and Vision
(slides 4) Visual Computing: Geometry, Graphics, and Vision
 
FINEVu CR-2i english manual - www.bilkamera.se
FINEVu CR-2i english manual - www.bilkamera.seFINEVu CR-2i english manual - www.bilkamera.se
FINEVu CR-2i english manual - www.bilkamera.se
 
091
091091
091
 
2013 6-6 a difference is a source of creation
2013 6-6 a difference is a source of creation2013 6-6 a difference is a source of creation
2013 6-6 a difference is a source of creation
 
Athletic Code Roundtable
Athletic Code RoundtableAthletic Code Roundtable
Athletic Code Roundtable
 
Information-Geometric Lenses for Multiple Foci + Contexts Interfaces
Information-Geometric Lenses for Multiple Foci + Contexts InterfacesInformation-Geometric Lenses for Multiple Foci + Contexts Interfaces
Information-Geometric Lenses for Multiple Foci + Contexts Interfaces
 
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 1) A Concise and Practical Introduction to Programming Algorithms in...
 
Projecting Computer Graphics on Moving Surfaces: A Simple Calibration and Tr...
Projecting Computer Graphics on Moving Surfaces: A Simple  Calibration and Tr...Projecting Computer Graphics on Moving Surfaces: A Simple  Calibration and Tr...
Projecting Computer Graphics on Moving Surfaces: A Simple Calibration and Tr...
 
Unit 4 home work
Unit 4 home workUnit 4 home work
Unit 4 home work
 
(ISIA 3) Cours d'algorithmique (1995)
(ISIA 3) Cours d'algorithmique (1995)(ISIA 3) Cours d'algorithmique (1995)
(ISIA 3) Cours d'algorithmique (1995)
 
THE IMPLEMENTATION OF COOPERATIVE LEARNING BY GIVING INITIAL KNOWLEDGE IN COL...
THE IMPLEMENTATION OF COOPERATIVE LEARNING BY GIVING INITIAL KNOWLEDGE IN COL...THE IMPLEMENTATION OF COOPERATIVE LEARNING BY GIVING INITIAL KNOWLEDGE IN COL...
THE IMPLEMENTATION OF COOPERATIVE LEARNING BY GIVING INITIAL KNOWLEDGE IN COL...
 
HOW TO CRACK IIT--BEST PROGRAMMES OF SRICHAITANYA:DRK RAO 9502 707070
HOW TO CRACK IIT--BEST PROGRAMMES OF SRICHAITANYA:DRK RAO 9502 707070HOW TO CRACK IIT--BEST PROGRAMMES OF SRICHAITANYA:DRK RAO 9502 707070
HOW TO CRACK IIT--BEST PROGRAMMES OF SRICHAITANYA:DRK RAO 9502 707070
 
Potential Genre 2
Potential Genre 2Potential Genre 2
Potential Genre 2
 
A new implementation of k-MLE for mixture modelling of Wishart distributions
A new implementation of k-MLE for mixture modelling of Wishart distributionsA new implementation of k-MLE for mixture modelling of Wishart distributions
A new implementation of k-MLE for mixture modelling of Wishart distributions
 
Layne Droz Video Game
Layne Droz Video GameLayne Droz Video Game
Layne Droz Video Game
 
Subjects to Consider When Developing Codes of Conduct
Subjects to Consider When Developing Codes of Conduct Subjects to Consider When Developing Codes of Conduct
Subjects to Consider When Developing Codes of Conduct
 
Audience research results and conclusions
Audience research  results and conclusionsAudience research  results and conclusions
Audience research results and conclusions
 
Gurumurthy Kalyanaram on Interpretation of Collective Bargaining Agreement (CBA)
Gurumurthy Kalyanaram on Interpretation of Collective Bargaining Agreement (CBA)Gurumurthy Kalyanaram on Interpretation of Collective Bargaining Agreement (CBA)
Gurumurthy Kalyanaram on Interpretation of Collective Bargaining Agreement (CBA)
 

Similar to (chapter 3) A Concise and Practical Introduction to Programming Algorithms in Java

(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
Frank Nielsen
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
KhurramKhan173
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
kavitha muneeshwaran
 
Programming in c function
Programming in c functionProgramming in c function
Programming in c function
Parvez Ahmed
 
functions
functionsfunctions
functions
Makwana Bhavesh
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
Functions
FunctionsFunctions
Functions
Mitali Chugh
 
Functions
FunctionsFunctions
Functions
Mitali Chugh
 
Unit 8
Unit 8Unit 8
Unit 8
rohassanie
 
Functions
FunctionsFunctions
Functions
Jesmin Akhter
 
User defined functions
User defined functionsUser defined functions
User defined functions
shubham_jangid
 
Functions12
Functions12Functions12
Functions12
sandhubuta
 
Functions123
Functions123 Functions123
Functions123
sandhubuta
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
chetan_p211
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
presentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.pptpresentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.ppt
SandipPradhan23
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Functional go
Functional goFunctional go
Functional go
Geison Goes
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Codemotion
 

Similar to (chapter 3) A Concise and Practical Introduction to Programming Algorithms in Java (20)

(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
(chapter 2) A Concise and Practical Introduction to Programming Algorithms in...
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Programming in c function
Programming in c functionProgramming in c function
Programming in c function
 
functions
functionsfunctions
functions
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Functions
FunctionsFunctions
Functions
 
Functions
FunctionsFunctions
Functions
 
Unit 8
Unit 8Unit 8
Unit 8
 
Functions
FunctionsFunctions
Functions
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Functions12
Functions12Functions12
Functions12
 
Functions123
Functions123 Functions123
Functions123
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
presentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.pptpresentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.ppt
 
Chap 9(functions)
Chap 9(functions)Chap 9(functions)
Chap 9(functions)
 
Functional go
Functional goFunctional go
Functional go
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 

Recently uploaded

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 

(chapter 3) A Concise and Practical Introduction to Programming Algorithms in Java

  • 1. 1A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Frank NIELSEN nielsen@lix.polytechnique.fr A Concise and Practical Introduction to Programming Algorithms in Java Chapter 3: Functions and recursivity
  • 2. 2A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen So far... Executive review Lecture 1: Java=Typed compiled programming language Variables: Type var; (boolean, int, long, float, double) Assignment: var=Expression; (with type checking) Expression: Operand1 Operator Operand2 (+-*/%) Instruction (;) & comments // or /* */
  • 3. 3A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen So far... Executive review Lecture 2: Program workflow (blocks/branching/loops) Determine the set of instructions at runtime Blocks: sequence of instructions { } Branching condition: if predicate B1 else B2 (switch case break) Loops: while, do, for and escaping break Numerical precisions: finite-precision arithmetic (absurd results, loose of associativity, etc.)
  • 4. 4A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Meaning of a function in mathematics ? ● Source (X) and target (Y) domains ● A map that associates to elements of X elements of Y ● An element of X is associated at most once to a member of Y ● The mapping gives always the same result (deterministic/no randomness) ● Functions of several variables may be built blockwise... ...using Cartesian product of spaces
  • 5. 5A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Meaning of functions for computing ? ● A portion of a program processing data and returning a result ●A function not returning a result is also called a procedure ●A function has typed parameters as arguments ●A function usually yields the same result for a given set of arguments (except for side-effects or use of pseudo-randomness) ● A function needs to be declared first before calling it elsewhere TypeF F(Type1 arg1, Type2 arg2, ..., TypeN argN) { TypeF result; block of instructions; return result; }
  • 6. 6A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen class INF311{ public static typeF F(type1 arg1, ..., typeN argN) { // Description Block of instructions; } ... } ● This kind of function is also called a static method ● Functions must be defined inside classes ● A function not returning a result has type void (also known as a procedure) Declaring functions in Java
  • 7. 7A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Defining the body of a function in Java Class INF311{ public static typeF F(type1 arg1, ..., typeN argN) { // Description Block of instructions; } } Body of a function ● Body should contain an instruction return to indicate the result ● If branching structures are used (if or switch) , a return should be written for all different branches. Otherwise we get acompiler error!
  • 8. 8A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Defining the body of a function in Java class INF311{ public static typeF F(type1 arg1, ..., typeN argN) { // Description Block of instructions; } } Body of a function Body should contain an instruction return to indicate the result If branching structures are used (if or switch) , then a return should be written for all different branches. ... Otherwise we get a compiler error! (why? => not type safe!)
  • 9. 9A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Using functions in Java
  • 10. 10A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen A few examples of basic functions class FuncDecl{ public static int square(int x) {return x*x;} public static boolean isOdd(int p) {if ((p%2)==0) return false; else return true;} public static double distance(double x, double y) {if (x>y) return x-y; else return y-x;} public static void display(double x, double y) {System.out.println("("+x+","+y+")"); return; // return void } public static void main (String[] args) { ... } }
  • 11. 11A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen class FuncDecl{ public static int square(int x){...} public static boolean isOdd(int p) {...} public static double distance(double x, double y) {...} public static void display(double x, double y) {...} public static void main (String[] args) { display(3,2); display(square(2),distance(5,9)); int p=123124345; if (isOdd(p)) System.out.println("p is odd"); else System.out.println("p is even"); } } A few examples of basic functions
  • 12. 12A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions... JCreator IDE
  • 13. 13A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen ● Modularity (ease of presentation) ● Code re-use (program once, re-use many times!) -> library (API) ● Ease certification of correctness and test routines. Benefits of using functions
  • 14. 14A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions with branching structures ERROR!!! This compiled but there is an error (break keyword?!)
  • 15. 15A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Functions with branching structures (correct program)
  • 16. 16A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Factorial function n! in Java Call function factorial in class « toolbox »
  • 17. 17A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Calling functions: Inner Mechanism TypeF result=F(param1, param2, ..., paramN); param1, ..., paramN should be of the same types as the ones declared in the function A function call can be used inside an expression, or even as a parameter of another function (nested calls) Example: F1(F2(x),F3(x)) Assignment's rule checks at compile time for type equivalence: System.out.println(IsPrime(23121971)); double dist=distance(u,v); Beyond the scope of the function's class, we need to put the function' class with a dot. Requires the function to be public. Math.cos(x); TD2.factorial(n); TC.lireInt();
  • 18. 18A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Revisiting IsPrime: measuring time We repeat this computation 1000 times to measure the elapsed time Function call in class TC: TC.demarrerChrono(); Function call in class TC: TC.tempsChrono();
  • 19. 19A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Potential side effects of functions: Static variables (effet de bord) ● Function that might modify/alterate the environment For example: ... displaying a value ... But also modify a variable of the base class ● A class variable is declared inside the class scope, ...not in function bodies ● Class variables are declared using the keyword static
  • 20. 20A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Side effects of functions: Static variables CountingCounting number ofnumber of function callsfunction calls Declaration of class variable static int classvar;
  • 21. 21A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Function: Signature and overloading signature of a function = ordered sequence of parameter types Two functions with different signatures can bear the same name (since the compiler can distinguish them!) static double plusone(...) int double String
  • 22. 22A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Although the function result type is important, Java does not take into account it for creating signatures... Function: Signature and overloading
  • 23. 23A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Function: Signature and overloading static int plusone (int n) static double plusone(int n) !!! COMPILATION ERROR !!! class SignatureError{ public static int plusone(int n) {return n+1;} public static double plusone(int n) {return n+1.0;} public static void main(String args[]) {} } C:JSignature.java:6: plusone(int) is already defined in SignatureError static double plusone(int n)
  • 24. 24A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Executing functions in Java ● Work place of the function is created when the function is called ● ... and destroyed once it is executed (value returned) ● Parameter values are equal to the results of the expressions ● Function parameters are allocated in memory reserved for the function ● If a parameter is modified inside the function body, it remains unchanged in the calling function. public static void main(String args[])
  • 25. 25A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Executing functions in Java Memory (stack) Memory for main Memory for Increment Memory for plusone As soon as we exit this function, k takes its original value of (5) passage par valeur
  • 26. 26A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Executing functions in Java (In C++, swapping is easy)
  • 27. 27A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Principle of recursion A beautiful principle of computing ! Loosely speaking, ... ...the inverse of inductivism in mathematics ● A function that calls itself... ● ...not forever, so that there should be stopping states... ● ...Function parameters should tend to the ones that do not ...require recursion to finalize the computation... But all this is an informal glimpse of recursion (self-structure)
  • 28. 28A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Example: Revisiting the factorial
  • 29. 29A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Population growth: Newly born pair of M/F rabbits are put in a field. Newly born rabbits take a month to become mature, after which time ... They produce a new pair of baby rabbits every month Q.: How many pairs will there be in subsequent years? Example: Fibonacci numbers Leonard de Pise (1170- 1245) 1, 1, 2, 3, 5, 8, 13, 21, 34, 55......
  • 30. 30A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Example: Fibonacci numbers Leonard de Pise Much better algorithms at.... http://fr.wikipedia.org/wiki/Suite_de_Fibonacci
  • 31. 31A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Understanding a recursive function recursive function called: ● Allocation of memory for local variables ● Stack operations to compute ● ... Call the function with other parameters, if required ● Process operations that remains on the stack int fibo(int n) {int x,y; if(n <= 1) return 1; x=fibo(n-1); y=fibo(n-2); return x+y;} x=fibo(2) y=fibo(1) return x+y fibo(3) Recursive calls
  • 32. 32A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen x=fibo(2) y=fibo(1) return x+y x=fibo(1) y=fibo(0) return x+y return 1; fibo(3) fibo(2) fibo(1) Understanding a recursive function
  • 33. 33A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen x=fibo(2) y=fibo(1) return x+y x=1 y=fibo(0) return x+y return 0; fibo(3) fibo(2) fibo(0) Understanding a recursive function
  • 34. 34A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen x=fibo(2) y=fibo(1) return x+y x=1 y=0 return x+yfibo(3) fibo(2)=1 Understanding a recursive function
  • 35. 35A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen x=1 y=fibo(1) return x+y fibo(3) fibo(1)=1 return 1; Understanding a recursive function
  • 36. 36A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen x=1 y=1 return x+y fibo(3)=2 As we can see, there is a lot of redundant work here. -> Very inefficient algorithm. Can cause stack overflow if the #recursive calls... ...become too large 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, .. Understanding a recursive function
  • 37. 37A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Understanding a recursive function
  • 38. 38A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Recursion: Halting problem When does a recursive program terminate? The arguments always decrease and there is always a stopping criterion
  • 39. 39A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Recursion: Halting problem
  • 40. 40A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Does not always halt because we may never reach terminal case (n=0) for odd numbers Recursion: Halting problem Do we always reach that terminal state?
  • 41. 41A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen What do you think of this one? Stack overflow Recursion: Halting problem
  • 42. 42A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Syracuse problem and termination conjecture Conjectured to halt (computer simulation helps intuition but does not give a full proof) Recursion: Halting problem
  • 43. 43A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen There is provably no algorithm that can take as input a program (binary string) and return true if and only if this program halts. http://en.wikipedia.org/wiki/Halting_problem Halting problem: Computer Science Proof skipped
  • 44. 44A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Terminal recursion Does not put function calls on the stack (thus avoid stack overflow) What happens if we call Factorial(100) ? Recursive calls are alwaysof the form return f(...); ->No instruction (computation) after the function (Factorial is not terminal since return n*f(n-1); ) if (n<=1) return 1; else return n*f(n-1);
  • 45. 45A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen factorial with terminal recursion Arguments plays the role of accumulators What happens if we call Factorial(100) ?
  • 46. 46A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Terminal Recursion: Revisiting Fibonacci 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, ... accum ulator
  • 47. 47A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Recursivity and Nature Drawing fractal curves and motifs Koch's snowflake Fractals: ● Patterns that are present at different scales ● The curve at stage n is defined recursively... ....from the curve at stage n-1
  • 48. 48A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Fractal: Sierpinski motif Generation 1 Generation 2 Generation 3 Generation 4 Generation 5 The recursive pattern is given by a simple rewritting rule: Replace a triangle by 3 triangles defined by the... midpoints of the edges of the source triangle Waclaw Sierpinski (1882-1969) Polish mathematician
  • 49. 49A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen Sierpinski curve (2D pyramid) http://www.enseignement.polytechnique.fr/profs/informatique/Philippe.Chassignet/MACLIB/Java/maclib_java.html
  • 50. 50A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen
  • 51. 51A Concise and Practical Introduction to Programming Algorithms in Java © 2009 Frank Nielsen