SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Tendances (20)

single linked list
single linked listsingle linked list
single linked list
 
Recursion - Algorithms and Data Structures
Recursion - Algorithms and Data StructuresRecursion - Algorithms and Data Structures
Recursion - Algorithms and Data Structures
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
 
Infix prefix postfix
Infix prefix postfixInfix prefix postfix
Infix prefix postfix
 
Sparse matrix
Sparse matrixSparse matrix
Sparse matrix
 
Introduction to data structure ppt
Introduction to data structure pptIntroduction to data structure ppt
Introduction to data structure ppt
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
Python Modules
Python ModulesPython Modules
Python Modules
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Heap sort
Heap sortHeap sort
Heap sort
 
Heaps
HeapsHeaps
Heaps
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Array ppt
Array pptArray ppt
Array ppt
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
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
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
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
 
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
 
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
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
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
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
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
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Dernier (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
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
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
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...
 
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
 
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-...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
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
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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
 
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 ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

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