Module 01 Stack and Recursion

Tushar B Kute
Tushar B KuteResearcher at http://mitu.co.in
See through C
Module 1
Stack and Recursion
Tushar B Kute
http://tusharkute.com
Overview
Subjects:
• Stacks
– Structure
– Methods
– Stacks and Method – Calls
• Recursion
– Principle
– Recursion and Stacks
– Examples
Stack: Properties
Answer:
They both provide LIFO (last in first out)
Structures
1
2
3
4
5
6
1
2
3
4
5
6
Stacks: Properties
Possible actions:
• PUSH an object (e.g. a plate) onto dispenser
• POP object out of dispenser
Stacks: Definition
Stacks are LIFO structures, providing
• Add Item (=PUSH) Methods
• Remove Item (=POP) Methods
They are a simple way to build a collection
• No indexing necessary
• Size of collection must not be predefined
• But: extremely reduced accessibility
A look into the JVM
1 int main( ) {
2 int a = 3;
3 int b = times(a);
4 printf(“%d“, b);
5 }
6 int times(int a) {
7 int b = 5;
8 int c = a * b;
9 return (c);
10 }
a = 3
a = 3
b
Return to LINE 3
b = 5
c = 15
A look into the compiler
...
9 return (c);
10 ...
a = 3
a = 3
b
Return to LINE 3
b = 5
c = 15
15
a = 3
b
Return to LINE 3
a = 3
b
c = 15
Return to LINE 3
Temporary storage
Clear Stack
A look into the CompilerA look into the
1 int main() {
2 int a = 3;
3 int b = times(a);
4 printf(“%d“, b);
5 }
a = 3
b
c = 15
Temporary storage
a = 3
b = 15
A look into the CompilerA look into the
1 int main() {
2 int a = 3;
3 int b = times(a);
4 printf(“%d“, b);
5 }
clear stack from local variables
A look into the CompilerA look into the
Important:
Every call to a function creates a
new set of local variables !
These Variables are created on the stack and
deleted when the function returns
Applications using a Stack
Examples:
• Finding Palindromes
• Bracket Parsing
• RPN
• RECURSION !
RecursionRecursion
RecursionRecursion
• Sometimes, the best way to solve a problem is
by solving a smaller version of the exact same
problem first
• Recursion is a technique that solves a
problem by solving a smaller problem of the
same type
• A function that is defined in terms of itself
RecursionRecursion
When you turn that into a program, you end
up with functions that call themselves:
Recursive Functions
RecursionRecursion
int fact (int a)
{
if (a==1)
return(1);
else
return (a * fact( a-1));
}
It computes f! (factorial)
What’s behind this function ?
Factorial:
a! = 1 * 2 * 3 * ... * (a-1) * a
Note:
a! = a * (a-1)!
remember:
...splitting up the problem into a smaller problem of the same type...
a!
a * (a-1)!
Factorial
int factorial(int a){
if (a==0)
return(1);
else
return(a * factorial( a-1));
}
Tracing the example
int factorial (int a){
if (a==1)
return(1);
else
return(a * factorial( a-1));
}
Watching the Stack
a = 5 a = 5 a = 5
Return to L4
a = 4
Return to L4
a = 4
Return to L4
a = 3
Return to L4
a = 2
Return to L4
a = 1
Initial After 1 recursion After 4th
recursion
…
Every call to the method creates a new set of local
variables !
int factorial(int a){
if (a==1)
return(1);
else
return(a * factorial( a-1));
}
Watching the Stack
a = 5
Return to L4
a = 4
Return to L4
a = 3
Return to L4
a = 2
Return to L4
a = 1
After 4th
recursion
a = 5
Return to L4
a = 4
Return to L4
a = 3
Return to L4
a = 2*1 = 2
a = 5
Return to L4
a = 4
Return to L4
a = 3*2 = 6
a = 5
Return to L4
a = 4*6 = 24
a = 5*24 = 120
Result
Problems that can be solved by recursion have these characteristics:
• One or more stopping cases have a simple, nonrecursive solution
• The other cases of the problem can be reduced (using recursion)
to problems that are closer to stopping cases
• Eventually the problem can be reduced to only stopping cases,
which are relatively easy to solve
Follow these steps to solve a recursive problem:
• Try to express the problem as a simpler version of itself
• Determine the stopping cases
• Determine the recursive steps
Properties of Recursive Functions
The recursive algorithms we write generally consist of an if statement:
IF
the stopping case is reached solve it
ELSE
split the problem into simpler cases using recursion
Solution
Solution on stack
Solution on stack
Solution on stack
Recursion does not terminate properly:
Stack Overflow !
Common Programming Error
Examples: Fractal Tree
http://id.mind.net/~zona/mmts/geometrySection/fractals/tree/treeFractal.html
Examples: The 8 Queens Problem
http://mossie.cs.und.ac.za/~murrellh/javademos/queens/queens.html
Eight queens are to be placed on a chess board
in such a way that no queen checks against
any other queen
Thank you
This presentation is created using LibreOffice Impress 3.6.2.2
1 of 25

Recommended

Data Structures- Part5 recursion by
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursionAbdullah Al-hazmy
9.4K views28 slides
stacks and queues by
stacks and queuesstacks and queues
stacks and queuesDurgaDeviCbit
612 views147 slides
My lecture stack_queue_operation by
My lecture stack_queue_operationMy lecture stack_queue_operation
My lecture stack_queue_operationSenthil Kumar
1.4K views62 slides
Stacks in c++ by
Stacks in c++Stacks in c++
Stacks in c++Vineeta Garg
8.6K views22 slides
Data structure lecture7 by
Data structure lecture7Data structure lecture7
Data structure lecture7Kumar
1.6K views43 slides
stack presentation by
stack presentationstack presentation
stack presentationShivalik college of engineering
8.9K views18 slides

More Related Content

What's hot

Data Structures - Searching & sorting by
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sortingKaushal Shah
13.6K views17 slides
Stacks and queues by
Stacks and queuesStacks and queues
Stacks and queuesTrupti Agrawal
788 views75 slides
Queues-handouts by
Queues-handoutsQueues-handouts
Queues-handoutsFajar Baskoro
567 views7 slides
Lecture 3 data structures & algorithms - sorting techniques - http://techiem... by
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...Dharmendra Prasad
2.1K views13 slides
Stack and its operations by
Stack and its operationsStack and its operations
Stack and its operationsV.V.Vanniaperumal College for Women
106 views21 slides
Sorting by
SortingSorting
SortingGhaffar Khan
11.2K views52 slides

What's hot(19)

Data Structures - Searching & sorting by Kaushal Shah
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
Kaushal Shah13.6K views
Lecture 3 data structures & algorithms - sorting techniques - http://techiem... by Dharmendra Prasad
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Dharmendra Prasad2.1K views
Sorting Seminar Presentation by Ashin Guha Majumder by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
Ashin Guha Majumder1.4K views
Stacks and queue by Amit Vats
Stacks and queueStacks and queue
Stacks and queue
Amit Vats947 views
03 stacks and_queues_using_arrays by tameemyousaf
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
tameemyousaf2.9K views

Similar to Module 01 Stack and Recursion

Cis068 08 by
Cis068 08Cis068 08
Cis068 08FALLEE31188
398 views32 slides
RecursionWeek8.ppt by
RecursionWeek8.pptRecursionWeek8.ppt
RecursionWeek8.pptkawtherabass1
2 views18 slides
Recursion and Sorting Algorithms by
Recursion and Sorting AlgorithmsRecursion and Sorting Algorithms
Recursion and Sorting AlgorithmsAfaq Mansoor Khan
613 views73 slides
recursion.ppt by
recursion.pptrecursion.ppt
recursion.pptgilvalerio
21 views24 slides
Recursion by
RecursionRecursion
RecursionJesmin Akhter
355 views20 slides
Functional Programming in Javascript - IL Tech Talks week by
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekyoavrubin
976 views103 slides

Similar to Module 01 Stack and Recursion(20)

Functional Programming in Javascript - IL Tech Talks week by yoavrubin
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin976 views
JDK8 Functional API by Justin Lin
JDK8 Functional APIJDK8 Functional API
JDK8 Functional API
Justin Lin18.7K views
Stack and its Applications : Data Structures ADT by Soumen Santra
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
Soumen Santra649 views
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA by Dheeraj Kataria
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIATypes Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Types Of Recursion in C++, Data Stuctures by DHEERAJ KATARIA
Dheeraj Kataria8.7K views
Stacks IN DATA STRUCTURES by Sowmya Jyothi
Stacks IN DATA STRUCTURESStacks IN DATA STRUCTURES
Stacks IN DATA STRUCTURES
Sowmya Jyothi1.2K views
Functional Python Webinar from October 22nd, 2014 by Reuven Lerner
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
Reuven Lerner1.1K views
lecture4-recursion.pptx by Lizhen Shi
lecture4-recursion.pptxlecture4-recursion.pptx
lecture4-recursion.pptx
Lizhen Shi14 views
Dsoop (co 221) 1 by Puja Koch
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
Puja Koch539 views
ScalaDays 2013 Keynote Speech by Martin Odersky by Typesafe
ScalaDays 2013 Keynote Speech by Martin OderskyScalaDays 2013 Keynote Speech by Martin Odersky
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe 14.1K views
Coordinate Descent method by Sanghyuk Chun
Coordinate Descent methodCoordinate Descent method
Coordinate Descent method
Sanghyuk Chun1.7K views
Lecture 01 variables scripts and operations by Smee Kaem Chann
Lecture 01   variables scripts and operationsLecture 01   variables scripts and operations
Lecture 01 variables scripts and operations
Smee Kaem Chann259 views

More from Tushar B Kute

Apache Pig: A big data processor by
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processorTushar B Kute
3.2K views50 slides
01 Introduction to Android by
01 Introduction to Android01 Introduction to Android
01 Introduction to AndroidTushar B Kute
868 views15 slides
Ubuntu OS and it's Flavours by
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's FlavoursTushar B Kute
1.7K views34 slides
Install Drupal in Ubuntu by Tushar B. Kute by
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. KuteTushar B Kute
893 views25 slides
Install Wordpress in Ubuntu Linux by Tushar B. Kute by
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteTushar B Kute
739 views26 slides
Share File easily between computers using sftp by
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftpTushar B Kute
2.2K views29 slides

More from Tushar B Kute(20)

Apache Pig: A big data processor by Tushar B Kute
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processor
Tushar B Kute3.2K views
01 Introduction to Android by Tushar B Kute
01 Introduction to Android01 Introduction to Android
01 Introduction to Android
Tushar B Kute868 views
Ubuntu OS and it's Flavours by Tushar B Kute
Ubuntu OS and it's FlavoursUbuntu OS and it's Flavours
Ubuntu OS and it's Flavours
Tushar B Kute1.7K views
Install Drupal in Ubuntu by Tushar B. Kute by Tushar B Kute
Install Drupal in Ubuntu by Tushar B. KuteInstall Drupal in Ubuntu by Tushar B. Kute
Install Drupal in Ubuntu by Tushar B. Kute
Tushar B Kute893 views
Install Wordpress in Ubuntu Linux by Tushar B. Kute by Tushar B Kute
Install Wordpress in Ubuntu Linux by Tushar B. KuteInstall Wordpress in Ubuntu Linux by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Tushar B Kute739 views
Share File easily between computers using sftp by Tushar B Kute
Share File easily between computers using sftpShare File easily between computers using sftp
Share File easily between computers using sftp
Tushar B Kute2.2K views
Signal Handling in Linux by Tushar B Kute
Signal Handling in LinuxSignal Handling in Linux
Signal Handling in Linux
Tushar B Kute10.4K views
Implementation of FIFO in Linux by Tushar B Kute
Implementation of FIFO in LinuxImplementation of FIFO in Linux
Implementation of FIFO in Linux
Tushar B Kute3.3K views
Implementation of Pipe in Linux by Tushar B Kute
Implementation of Pipe in LinuxImplementation of Pipe in Linux
Implementation of Pipe in Linux
Tushar B Kute5.2K views
Basic Multithreading using Posix Threads by Tushar B Kute
Basic Multithreading using Posix ThreadsBasic Multithreading using Posix Threads
Basic Multithreading using Posix Threads
Tushar B Kute1.5K views
Part 04 Creating a System Call in Linux by Tushar B Kute
Part 04 Creating a System Call in LinuxPart 04 Creating a System Call in Linux
Part 04 Creating a System Call in Linux
Tushar B Kute3.8K views
Part 03 File System Implementation in Linux by Tushar B Kute
Part 03 File System Implementation in LinuxPart 03 File System Implementation in Linux
Part 03 File System Implementation in Linux
Tushar B Kute3.4K views
Part 02 Linux Kernel Module Programming by Tushar B Kute
Part 02 Linux Kernel Module ProgrammingPart 02 Linux Kernel Module Programming
Part 02 Linux Kernel Module Programming
Tushar B Kute3.6K views
Part 01 Linux Kernel Compilation (Ubuntu) by Tushar B Kute
Part 01 Linux Kernel Compilation (Ubuntu)Part 01 Linux Kernel Compilation (Ubuntu)
Part 01 Linux Kernel Compilation (Ubuntu)
Tushar B Kute3.7K views
Open source applications softwares by Tushar B Kute
Open source applications softwaresOpen source applications softwares
Open source applications softwares
Tushar B Kute1K views
Introduction to Ubuntu Edge Operating System (Ubuntu Touch) by Tushar B Kute
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Tushar B Kute5.6K views
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B KuteUnit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Tushar B Kute3.9K views
Technical blog by Engineering Students of Sandip Foundation, itsitrc by Tushar B Kute
Technical blog by Engineering Students of Sandip Foundation, itsitrcTechnical blog by Engineering Students of Sandip Foundation, itsitrc
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Tushar B Kute870 views
Chapter 01 Introduction to Java by Tushar B Kute by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute3K views
Chapter 02: Classes Objects and Methods Java by Tushar B Kute by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Tushar B Kute8.4K views

Recently uploaded

Benefits in Software Development by
Benefits in Software DevelopmentBenefits in Software Development
Benefits in Software DevelopmentJohn Valentino
5 views15 slides
Introduction to Git Source Control by
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source ControlJohn Valentino
7 views18 slides
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...NimaTorabi2
16 views17 slides
Electronic AWB - Electronic Air Waybill by
Electronic AWB - Electronic Air Waybill Electronic AWB - Electronic Air Waybill
Electronic AWB - Electronic Air Waybill Freightoscope
5 views1 slide
Introduction to Maven by
Introduction to MavenIntroduction to Maven
Introduction to MavenJohn Valentino
6 views10 slides
The Era of Large Language Models.pptx by
The Era of Large Language Models.pptxThe Era of Large Language Models.pptx
The Era of Large Language Models.pptxAbdulVahedShaik
7 views9 slides

Recently uploaded(20)

Introduction to Git Source Control by John Valentino
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source Control
John Valentino7 views
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi216 views
Electronic AWB - Electronic Air Waybill by Freightoscope
Electronic AWB - Electronic Air Waybill Electronic AWB - Electronic Air Waybill
Electronic AWB - Electronic Air Waybill
Freightoscope 5 views
360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492162 views
Automated Testing of Microsoft Power BI Reports by RTTS
Automated Testing of Microsoft Power BI ReportsAutomated Testing of Microsoft Power BI Reports
Automated Testing of Microsoft Power BI Reports
RTTS8 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254558 views
AI and Ml presentation .pptx by FayazAli87
AI and Ml presentation .pptxAI and Ml presentation .pptx
AI and Ml presentation .pptx
FayazAli8714 views
Top-5-production-devconMunich-2023.pptx by Tier1 app
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
Tier1 app9 views
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile... by Stefan Wolpers
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
How To Make Your Plans Suck Less — Maarten Dalmijn at the 57th Hands-on Agile...
Stefan Wolpers33 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated... by TomHalpin9
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
Dev-HRE-Ops - Addressing the _Last Mile DevOps Challenge_ in Highly Regulated...
TomHalpin96 views
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
predicting-m3-devopsconMunich-2023.pptx by Tier1 app
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app8 views

Module 01 Stack and Recursion

  • 1. See through C Module 1 Stack and Recursion Tushar B Kute http://tusharkute.com
  • 2. Overview Subjects: • Stacks – Structure – Methods – Stacks and Method – Calls • Recursion – Principle – Recursion and Stacks – Examples
  • 3. Stack: Properties Answer: They both provide LIFO (last in first out) Structures 1 2 3 4 5 6 1 2 3 4 5 6
  • 4. Stacks: Properties Possible actions: • PUSH an object (e.g. a plate) onto dispenser • POP object out of dispenser
  • 5. Stacks: Definition Stacks are LIFO structures, providing • Add Item (=PUSH) Methods • Remove Item (=POP) Methods They are a simple way to build a collection • No indexing necessary • Size of collection must not be predefined • But: extremely reduced accessibility
  • 6. A look into the JVM 1 int main( ) { 2 int a = 3; 3 int b = times(a); 4 printf(“%d“, b); 5 } 6 int times(int a) { 7 int b = 5; 8 int c = a * b; 9 return (c); 10 } a = 3 a = 3 b Return to LINE 3 b = 5 c = 15
  • 7. A look into the compiler ... 9 return (c); 10 ... a = 3 a = 3 b Return to LINE 3 b = 5 c = 15 15 a = 3 b Return to LINE 3 a = 3 b c = 15 Return to LINE 3 Temporary storage Clear Stack
  • 8. A look into the CompilerA look into the 1 int main() { 2 int a = 3; 3 int b = times(a); 4 printf(“%d“, b); 5 } a = 3 b c = 15 Temporary storage a = 3 b = 15
  • 9. A look into the CompilerA look into the 1 int main() { 2 int a = 3; 3 int b = times(a); 4 printf(“%d“, b); 5 } clear stack from local variables
  • 10. A look into the CompilerA look into the Important: Every call to a function creates a new set of local variables ! These Variables are created on the stack and deleted when the function returns
  • 11. Applications using a Stack Examples: • Finding Palindromes • Bracket Parsing • RPN • RECURSION !
  • 13. RecursionRecursion • Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first • Recursion is a technique that solves a problem by solving a smaller problem of the same type • A function that is defined in terms of itself
  • 14. RecursionRecursion When you turn that into a program, you end up with functions that call themselves: Recursive Functions
  • 15. RecursionRecursion int fact (int a) { if (a==1) return(1); else return (a * fact( a-1)); } It computes f! (factorial) What’s behind this function ?
  • 16. Factorial: a! = 1 * 2 * 3 * ... * (a-1) * a Note: a! = a * (a-1)! remember: ...splitting up the problem into a smaller problem of the same type... a! a * (a-1)! Factorial
  • 17. int factorial(int a){ if (a==0) return(1); else return(a * factorial( a-1)); } Tracing the example
  • 18. int factorial (int a){ if (a==1) return(1); else return(a * factorial( a-1)); } Watching the Stack a = 5 a = 5 a = 5 Return to L4 a = 4 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2 Return to L4 a = 1 Initial After 1 recursion After 4th recursion … Every call to the method creates a new set of local variables !
  • 19. int factorial(int a){ if (a==1) return(1); else return(a * factorial( a-1)); } Watching the Stack a = 5 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2 Return to L4 a = 1 After 4th recursion a = 5 Return to L4 a = 4 Return to L4 a = 3 Return to L4 a = 2*1 = 2 a = 5 Return to L4 a = 4 Return to L4 a = 3*2 = 6 a = 5 Return to L4 a = 4*6 = 24 a = 5*24 = 120 Result
  • 20. Problems that can be solved by recursion have these characteristics: • One or more stopping cases have a simple, nonrecursive solution • The other cases of the problem can be reduced (using recursion) to problems that are closer to stopping cases • Eventually the problem can be reduced to only stopping cases, which are relatively easy to solve Follow these steps to solve a recursive problem: • Try to express the problem as a simpler version of itself • Determine the stopping cases • Determine the recursive steps Properties of Recursive Functions
  • 21. The recursive algorithms we write generally consist of an if statement: IF the stopping case is reached solve it ELSE split the problem into simpler cases using recursion Solution Solution on stack Solution on stack Solution on stack
  • 22. Recursion does not terminate properly: Stack Overflow ! Common Programming Error
  • 24. Examples: The 8 Queens Problem http://mossie.cs.und.ac.za/~murrellh/javademos/queens/queens.html Eight queens are to be placed on a chess board in such a way that no queen checks against any other queen
  • 25. Thank you This presentation is created using LibreOffice Impress 3.6.2.2