SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Graph in data structure
Graph in data structureGraph in data structure
Graph in data structureAbrish06
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries LectureFelipe Costa
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureBalwant Gorad
 
Graph representation
Graph representationGraph representation
Graph representationTech_MX
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithmMohd Arif
 
Binary search in data structure
Binary search in data structureBinary search in data structure
Binary search in data structureMeherul1234
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary treeKrish_ver2
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTSoumen Santra
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First SearchKevin Jadiya
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFSRajandeep Gill
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree Divya Ks
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsDrishti Bhalla
 

Was ist angesagt? (20)

Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
Merge sort
Merge sortMerge sort
Merge sort
 
Binary Search
Binary SearchBinary Search
Binary Search
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
 
stack & queue
stack & queuestack & queue
stack & queue
 
Linked List
Linked ListLinked List
Linked List
 
Graph representation
Graph representationGraph representation
Graph representation
 
Dinive conquer algorithm
Dinive conquer algorithmDinive conquer algorithm
Dinive conquer algorithm
 
STL in C++
STL in C++STL in C++
STL in C++
 
Binary search in data structure
Binary search in data structureBinary search in data structure
Binary search in data structure
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
Breadth First Search & Depth First Search
Breadth First Search & Depth First SearchBreadth First Search & Depth First Search
Breadth First Search & Depth First Search
 
Graph traversal-BFS & DFS
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
 

Ähnlich wie 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.pdfSubhendraBasu4
 
Module 01 Stack and Recursion
Module 01 Stack and RecursionModule 01 Stack and Recursion
Module 01 Stack and RecursionTushar B Kute
 
(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 weekyoavrubin
 
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 NotesAndres 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 cSaule 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 .docxeugeniadean34240
 
Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfAkashSingh625550
 
Recursion and Sorting Algorithms
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
 
lab-8 (1).pptx
lab-8 (1).pptxlab-8 (1).pptx
lab-8 (1).pptxShimoFcis
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptMahyuddin8
 
ch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptch02-primitive-data-definite-loops.ppt
ch02-primitive-data-definite-loops.pptghoitsun
 
C++ Programming Basics.pptx
C++ Programming Basics.pptxC++ Programming Basics.pptx
C++ Programming Basics.pptxZntalemAbebe
 
daa-unit-3-greedy method
daa-unit-3-greedy methoddaa-unit-3-greedy method
daa-unit-3-greedy methodhodcsencet
 

Ähnlich wie 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
 

Mehr von 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 AfghanistanAbdul Rahman Sherzad
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsAbdul Rahman Sherzad
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLAbdul Rahman Sherzad
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and ApplicationsAbdul 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 AwarenessAbdul 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 SchedulersAbdul 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 UniversitiesAbdul 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 ExplanationAbdul 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 AnswersAbdul Rahman Sherzad
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsAbdul 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 StepAbdul 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 JavaAbdul 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 TechnologiesAbdul 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 ClassesAbdul Rahman Sherzad
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesAbdul Rahman Sherzad
 

Mehr von 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
 

Kürzlich hochgeladen

Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Kürzlich hochgeladen (20)

Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

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