SlideShare a Scribd company logo
Iterations
and
Recursions
Abdul Rahman Sherzad
Lecturer at Compute Science faculty
Herat University
Recursive Method?
• A recursive method is a method that calls itself.
• There are two key requirements in order to make sure that
the recursion is successful:
 With each call the problem should become smaller and simpler.
 The method will eventually should lead to a point where no longer
calls itself – This point is called the base case.
 When the recursive method is called with a base case, the result is returned to
the previous method calls until the original call of the method eventually
returns the final result. 2
Iteration
• Repeated execution of a set of instructions is called iteration.
• It is the act of repeating a process
 to perform specific action on a collection of elements, one at a time,
 each repetition of the process is called an iteration,
 The results of one iteration are used as the starting point for the next iteration
until the condition is met.
• Iteration is most commonly expressed using loop statements.
 For statement
 While statement
 Do While statement 3
Factorial
• Factorial of a non-negative integer n is the product of all
positive integers less than or equal to n.
 5! = 5 * 4 * 3 * 2 * 1  120
• Factorial of n is denoted by n!
• Factorial of 0 is 1.
• Factorial for a negative number does not exist.
4
Factorial – Recursion
5
factorial(5)- Recursion Execution
• This slide illustrates recursive steps computing 5!
 Step 1: 5 * factorial(4)
 Step 2: 4 * factorial(3)
 Step 3: 3 * factorial(2)
 Step 4: 2 * factorial(1)
 Step 5: 1
6
Step 6: return 1
Step 7: return 2 * 1  2
Step 8: return 3 * 2  6
Step 9: return 4 * 6  24
Step 10: return 5 * 24  120
Factorial – Iteration
7
factorial(5)- Iteration Execution
• This slide illustrates recursive steps computing 5!
 Step 1: result = result * 5  result = 1 * 5
 Step 2: result = result * 4  result = 5 * 4
 Step 3: result = result * 3  result = 20 * 3
 Step 4: result = result * 2  result = 60 * 2
 Step 5: return result  return 120
8
Fibonacci Number
• The Fibonacci sequence is a series of numbers where a number is
found by adding up the two numbers preceding it.
• The Fibonacci sequence beings with 0 and 1.
• The Fibonacci sequence is written as a rule as follow:
 Fibonaccin = Fibonaccin-1 + Fibonaccin-2
• The first 11 Fibonacci numbers Fibonaccin for n = 0, 1, 2, … , 11 are:
9
F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10
0 1 1 2 3 5 8 13 21 34 55
Fibonacci – Recursion
10
fibonacci(5)- Recursion Execution
fibonacci(5)
fibonacci(4)
fibonacci(3)
fibonacci(2)
fibonacci(1) fibonacci(0)
fibonacci(1)
fibonacci(2)
fibonacci(1) fibonacci(0)
fibonacci(3)
fibonacci(2)
fibonacci(1) fibonacci(0)
fibonacci(1)
11
1 0
1 1
2
1 0 1 0
11
3
1
2
5
Fibonacci – Iteration
12
GCD (Greatest Common Divisor)
• To calculate and find the Greatest Common Divisor (GCD) of two
integer numbers num1 and num2 using Euclid’s algorithm is
another great and suited example demonstrating recursion.
• Euclidean algorithm is defined as follow:
 if num2 == 0 then GCD (num1, num2) is num1
 else GCD (num1, num2) is GCD (num2, modulus(num1 / num2))
• Note: The modulus is the remainder when num1 is divided by
num2 and it is computed in Java by using the % operator.
13
GCD – Recursion
14
gcd(120, 35)-Recursion Execution
• Following steps illustrate calculating gcd(187, 77):
 Step 1: gcd(120, 35)
 Step 2: gcd(35, 15)
 Step 3: gcd(15, 5)
 Step 4: gcd(5, 0)
 Step 5: 5
15
Step 6: return 5
Step 7: return 5
Step 8: return 5
Step 9: return 5
Step 10: return 5
GCD – Iteration
16
Binary Search
• Binary search – also called half-interval search, logarithmic search or
binary chop – is a search algorithm that finds the position of a target value
within a sorted array.
• Binary search is a fast and efficient search algorithm with run-time
complexity of Ο(log n).
• Binary search works on the principle of divide and conquer.
• Binary search compares the target value to the middle element of the array:
 If they are equal, then the index of item is returned.
 If they are unequal, the half in which the target cannot lie is eliminated and the search
continues on the remaining half until it is successful.
 If the search ends with the remaining half being empty, the target is not in the array. 17
Binary Search - Recursion
18
binarySearch(input,0, 7, 25)-Recursion Execution
1 5 10 20middle 25target 30 44 55
19
binarySearch(input, 0, 7, 25) middle = (0 + 7) / 2  3, check sortedArray[3]
1 5 10 20 25target 30middle 44 55
binarySearch(input, 4, 7, 25) middle = (4 + 7) / 2  5, check sortedArray[5]
They are not match; target value ‘25’ is > middle value ‘20’. Hence …
1 5 10 20 25target middle 30 44 55
binarySearch(input, 4, 4, 25) middle = (4 + 4) / 2  4, check sortedArray[4]
They are not match; target value ‘25’ is < middle value ‘30’. Hence …
They are matched; target value ‘25’ is == middle value ‘25’. Hence …
return middle;  return 4;
Binary Search - Iteration
20
Traverse Directory and Sub-Directories
21
Traverse Directory and Sub-Directories -
Recursion
22
Traverse Directory and Sub-
Directories - Recursion
• In such particular cases, recursive solutions are probably
better and efficient than non-recursive ones (Iteration and
Stack).
• Additionally, recursive solutions are easier to code as well as
easier to understand than the non-recursive ones.
• Caution:
 The only potential problem with recursions are that they overflow the
stack if the directory tree is intensively deep.
23
Traverse Directory and Sub-Directories –
Iteration and Stack
24
Traverse Directory and Sub-
Directories - Iteration
• In such cases, Iteration and Stack together are alternative solutions to avoid
recursions.
• Instead of recursive calls, the list containing the current directory’s files are pushed
onto the Stack.
 In this case, all items inside the parent directory are pushed onto the Stack.
• Then the new directory is read in order to traverse them.
 In this case, all the items inside the son directory are also pushed onto the Stack.
• When this processed is finished, the files are popped from the Stack.
 In this case, all the files inside the son directory, then all the files inside the nephew
directory and finally continue with the parent directory.
• This will give you a Depth-First traversal. 25
Conclusion
• There are similarities between recursion and iteration.
• Actually, any problems that can be solved with iterations can be done with
recursions.
 There are some programming languages that use recursion exclusively.
• In the factorial, greatest common divisor and binary search problems,
the iterative and recursive solutions use roughly the same algorithms,
and their efficiency is approximately the same.
• In the exponentiation problem e.g. Fibonacci;
 the iterative solution takes linear time to complete,
 while the recursive solution executes in log time.
26
Conclusion
• There are some problems that are simple to solve with recursions,
but they are comparatively difficult to solve with iterations (e.g. tree
traversal).
• Iterations are recommended for algorithms that are easier to explain
in terms of iterations.
• Recursions are good a problem can be solved by divide and conquer
technique (e.g. Searching binary trees).
 Warning: Infinite recursion causes a Stack Overflow Error!
27
28

More Related Content

What's hot

Data Representation
Data RepresentationData Representation
Data Representation
Dilum Bandara
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Regular expressions-Theory of computation
Regular expressions-Theory of computationRegular expressions-Theory of computation
Regular expressions-Theory of computation
Bipul Roy Bpl
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notationsNikhil Sharma
 
Linked list
Linked listLinked list
Linked list
KalaivaniKS1
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Chapter 12 ds
Chapter 12 dsChapter 12 ds
Chapter 12 ds
Hanif Durad
 
Nested loops
Nested loopsNested loops
Nested loops
Neeru Mittal
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
Dharita Chokshi
 
Queue ppt
Queue pptQueue ppt
Queue ppt
SouravKumar328
 
Hashing
HashingHashing
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
Zia Ush Shamszaman
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
Protap Mondal
 
Stressen's matrix multiplication
Stressen's matrix multiplicationStressen's matrix multiplication
Stressen's matrix multiplicationKumar
 
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
Akshaya Arunan
 
Arrays
ArraysArrays
Binary Search
Binary SearchBinary Search
Binary Search
kunj desai
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
Meghaj Mallick
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
Masud Parvaze
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 

What's hot (20)

Data Representation
Data RepresentationData Representation
Data Representation
 
Inline function
Inline functionInline function
Inline function
 
Regular expressions-Theory of computation
Regular expressions-Theory of computationRegular expressions-Theory of computation
Regular expressions-Theory of computation
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Linked list
Linked listLinked list
Linked list
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Chapter 12 ds
Chapter 12 dsChapter 12 ds
Chapter 12 ds
 
Nested loops
Nested loopsNested loops
Nested loops
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Hashing
HashingHashing
Hashing
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Stressen's matrix multiplication
Stressen's matrix multiplicationStressen's matrix multiplication
Stressen's matrix multiplication
 
Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
 
Arrays
ArraysArrays
Arrays
 
Binary Search
Binary SearchBinary Search
Binary Search
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 

Similar to Iterations and Recursions

Algorithm Intfact - 14 July 2022 - Part A.pdf
Algorithm Intfact - 14 July 2022 - Part A.pdfAlgorithm Intfact - 14 July 2022 - Part A.pdf
Algorithm Intfact - 14 July 2022 - Part A.pdf
SubhendraBasu4
 
8282967.ppt
8282967.ppt8282967.ppt
8282967.ppt
ArunachalamSelva
 
Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
Flavia Tembo Kambale
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
Tushar B Kute
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
jinalgoti
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sortingFadhil Ismail
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
Andres Mendez-Vazquez
 
Lecture 5 numbers and built in functions
Lecture 5  numbers and built in functionsLecture 5  numbers and built in functions
Lecture 5 numbers and built in functionsalvin567
 
Recursion, debugging in c
Recursion, debugging in cRecursion, debugging in c
Recursion, debugging in c
Saule Anay
 
1_Introduction.pdf1 Dynamics and Control Topic .docx
1_Introduction.pdf1 Dynamics and Control  Topic .docx1_Introduction.pdf1 Dynamics and Control  Topic .docx
1_Introduction.pdf1 Dynamics and Control Topic .docx
eugeniadean34240
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
AkashSingh625550
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
Afaq Mansoor Khan
 
lab-8 (1).pptx
lab-8 (1).pptxlab-8 (1).pptx
lab-8 (1).pptx
ShimoFcis
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
Mahyuddin8
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
ghoitsun
 
C++ Programming Basics.pptx
C++ Programming Basics.pptxC++ Programming Basics.pptx
C++ Programming Basics.pptx
ZntalemAbebe
 
Greedy method
Greedy methodGreedy method
Greedy method
Anusha sivakumar
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
hodcsencet
 
Recursion
RecursionRecursion
Recursion
Malainine Zaid
 

Similar to Iterations and Recursions (20)

Algorithm Intfact - 14 July 2022 - Part A.pdf
Algorithm Intfact - 14 July 2022 - Part A.pdfAlgorithm Intfact - 14 July 2022 - Part A.pdf
Algorithm Intfact - 14 July 2022 - Part A.pdf
 
8282967.ppt
8282967.ppt8282967.ppt
8282967.ppt
 
Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and Recursion
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
 
Lecture 5 numbers and built in functions
Lecture 5  numbers and built in functionsLecture 5  numbers and built in functions
Lecture 5 numbers and built in functions
 
Recursion, debugging in c
Recursion, debugging in cRecursion, debugging in c
Recursion, debugging in c
 
1_Introduction.pdf1 Dynamics and Control Topic .docx
1_Introduction.pdf1 Dynamics and Control  Topic .docx1_Introduction.pdf1 Dynamics and Control  Topic .docx
1_Introduction.pdf1 Dynamics and Control Topic .docx
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting Algorithms
 
lab-8 (1).pptx
lab-8 (1).pptxlab-8 (1).pptx
lab-8 (1).pptx
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.ppt
 
C++ Programming Basics.pptx
C++ Programming Basics.pptxC++ Programming Basics.pptx
C++ Programming Basics.pptx
 
Greedy method
Greedy methodGreedy method
Greedy method
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy method
 
Recursion
RecursionRecursion
Recursion
 

More from Abdul Rahman Sherzad

Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Abdul Rahman Sherzad
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation Snippets
Abdul Rahman Sherzad
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQL
Abdul Rahman Sherzad
 
PHP Variable variables Examples
PHP Variable variables ExamplesPHP Variable variables Examples
PHP Variable variables Examples
Abdul Rahman Sherzad
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and Applications
Abdul Rahman Sherzad
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Abdul Rahman Sherzad
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
Abdul Rahman Sherzad
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
Abdul Rahman Sherzad
 
Mobile Score Notification System
Mobile Score Notification SystemMobile Score Notification System
Mobile Score Notification System
Abdul Rahman Sherzad
 
Herat Innovation Lab 2015
Herat Innovation Lab 2015Herat Innovation Lab 2015
Herat Innovation Lab 2015
Abdul Rahman Sherzad
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan Universities
Abdul Rahman Sherzad
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
Abdul Rahman Sherzad
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
Abdul Rahman Sherzad
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
Abdul Rahman Sherzad
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
Abdul Rahman Sherzad
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
Abdul Rahman Sherzad
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Abdul Rahman Sherzad
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
Abdul Rahman Sherzad
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Abdul Rahman Sherzad
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
Abdul Rahman Sherzad
 

More from Abdul Rahman Sherzad (20)

Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation Snippets
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQL
 
PHP Variable variables Examples
PHP Variable variables ExamplesPHP Variable variables Examples
PHP Variable variables Examples
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and Applications
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
Mobile Score Notification System
Mobile Score Notification SystemMobile Score Notification System
Mobile Score Notification System
 
Herat Innovation Lab 2015
Herat Innovation Lab 2015Herat Innovation Lab 2015
Herat Innovation Lab 2015
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan Universities
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
 

Recently uploaded

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 

Recently uploaded (20)

Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

Iterations and Recursions

  • 1. Iterations and Recursions Abdul Rahman Sherzad Lecturer at Compute Science faculty Herat University
  • 2. Recursive Method? • A recursive method is a method that calls itself. • There are two key requirements in order to make sure that the recursion is successful:  With each call the problem should become smaller and simpler.  The method will eventually should lead to a point where no longer calls itself – This point is called the base case.  When the recursive method is called with a base case, the result is returned to the previous method calls until the original call of the method eventually returns the final result. 2
  • 3. Iteration • Repeated execution of a set of instructions is called iteration. • It is the act of repeating a process  to perform specific action on a collection of elements, one at a time,  each repetition of the process is called an iteration,  The results of one iteration are used as the starting point for the next iteration until the condition is met. • Iteration is most commonly expressed using loop statements.  For statement  While statement  Do While statement 3
  • 4. Factorial • Factorial of a non-negative integer n is the product of all positive integers less than or equal to n.  5! = 5 * 4 * 3 * 2 * 1  120 • Factorial of n is denoted by n! • Factorial of 0 is 1. • Factorial for a negative number does not exist. 4
  • 6. factorial(5)- Recursion Execution • This slide illustrates recursive steps computing 5!  Step 1: 5 * factorial(4)  Step 2: 4 * factorial(3)  Step 3: 3 * factorial(2)  Step 4: 2 * factorial(1)  Step 5: 1 6 Step 6: return 1 Step 7: return 2 * 1  2 Step 8: return 3 * 2  6 Step 9: return 4 * 6  24 Step 10: return 5 * 24  120
  • 8. factorial(5)- Iteration Execution • This slide illustrates recursive steps computing 5!  Step 1: result = result * 5  result = 1 * 5  Step 2: result = result * 4  result = 5 * 4  Step 3: result = result * 3  result = 20 * 3  Step 4: result = result * 2  result = 60 * 2  Step 5: return result  return 120 8
  • 9. Fibonacci Number • The Fibonacci sequence is a series of numbers where a number is found by adding up the two numbers preceding it. • The Fibonacci sequence beings with 0 and 1. • The Fibonacci sequence is written as a rule as follow:  Fibonaccin = Fibonaccin-1 + Fibonaccin-2 • The first 11 Fibonacci numbers Fibonaccin for n = 0, 1, 2, … , 11 are: 9 F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 0 1 1 2 3 5 8 13 21 34 55
  • 11. fibonacci(5)- Recursion Execution fibonacci(5) fibonacci(4) fibonacci(3) fibonacci(2) fibonacci(1) fibonacci(0) fibonacci(1) fibonacci(2) fibonacci(1) fibonacci(0) fibonacci(3) fibonacci(2) fibonacci(1) fibonacci(0) fibonacci(1) 11 1 0 1 1 2 1 0 1 0 11 3 1 2 5
  • 13. GCD (Greatest Common Divisor) • To calculate and find the Greatest Common Divisor (GCD) of two integer numbers num1 and num2 using Euclid’s algorithm is another great and suited example demonstrating recursion. • Euclidean algorithm is defined as follow:  if num2 == 0 then GCD (num1, num2) is num1  else GCD (num1, num2) is GCD (num2, modulus(num1 / num2)) • Note: The modulus is the remainder when num1 is divided by num2 and it is computed in Java by using the % operator. 13
  • 15. gcd(120, 35)-Recursion Execution • Following steps illustrate calculating gcd(187, 77):  Step 1: gcd(120, 35)  Step 2: gcd(35, 15)  Step 3: gcd(15, 5)  Step 4: gcd(5, 0)  Step 5: 5 15 Step 6: return 5 Step 7: return 5 Step 8: return 5 Step 9: return 5 Step 10: return 5
  • 17. Binary Search • Binary search – also called half-interval search, logarithmic search or binary chop – is a search algorithm that finds the position of a target value within a sorted array. • Binary search is a fast and efficient search algorithm with run-time complexity of Ο(log n). • Binary search works on the principle of divide and conquer. • Binary search compares the target value to the middle element of the array:  If they are equal, then the index of item is returned.  If they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful.  If the search ends with the remaining half being empty, the target is not in the array. 17
  • 18. Binary Search - Recursion 18
  • 19. binarySearch(input,0, 7, 25)-Recursion Execution 1 5 10 20middle 25target 30 44 55 19 binarySearch(input, 0, 7, 25) middle = (0 + 7) / 2  3, check sortedArray[3] 1 5 10 20 25target 30middle 44 55 binarySearch(input, 4, 7, 25) middle = (4 + 7) / 2  5, check sortedArray[5] They are not match; target value ‘25’ is > middle value ‘20’. Hence … 1 5 10 20 25target middle 30 44 55 binarySearch(input, 4, 4, 25) middle = (4 + 4) / 2  4, check sortedArray[4] They are not match; target value ‘25’ is < middle value ‘30’. Hence … They are matched; target value ‘25’ is == middle value ‘25’. Hence … return middle;  return 4;
  • 20. Binary Search - Iteration 20
  • 21. Traverse Directory and Sub-Directories 21
  • 22. Traverse Directory and Sub-Directories - Recursion 22
  • 23. Traverse Directory and Sub- Directories - Recursion • In such particular cases, recursive solutions are probably better and efficient than non-recursive ones (Iteration and Stack). • Additionally, recursive solutions are easier to code as well as easier to understand than the non-recursive ones. • Caution:  The only potential problem with recursions are that they overflow the stack if the directory tree is intensively deep. 23
  • 24. Traverse Directory and Sub-Directories – Iteration and Stack 24
  • 25. Traverse Directory and Sub- Directories - Iteration • In such cases, Iteration and Stack together are alternative solutions to avoid recursions. • Instead of recursive calls, the list containing the current directory’s files are pushed onto the Stack.  In this case, all items inside the parent directory are pushed onto the Stack. • Then the new directory is read in order to traverse them.  In this case, all the items inside the son directory are also pushed onto the Stack. • When this processed is finished, the files are popped from the Stack.  In this case, all the files inside the son directory, then all the files inside the nephew directory and finally continue with the parent directory. • This will give you a Depth-First traversal. 25
  • 26. Conclusion • There are similarities between recursion and iteration. • Actually, any problems that can be solved with iterations can be done with recursions.  There are some programming languages that use recursion exclusively. • In the factorial, greatest common divisor and binary search problems, the iterative and recursive solutions use roughly the same algorithms, and their efficiency is approximately the same. • In the exponentiation problem e.g. Fibonacci;  the iterative solution takes linear time to complete,  while the recursive solution executes in log time. 26
  • 27. Conclusion • There are some problems that are simple to solve with recursions, but they are comparatively difficult to solve with iterations (e.g. tree traversal). • Iterations are recommended for algorithms that are easier to explain in terms of iterations. • Recursions are good a problem can be solved by divide and conquer technique (e.g. Searching binary trees).  Warning: Infinite recursion causes a Stack Overflow Error! 27
  • 28. 28