SFTW120-LectureNotes-18 - SFTW120 Programming Science...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 SFTW120 Programming Science Lecture Notes 18: C: Recursion © Robert P. Biuk-Aghai SFTW120 - Programming Science 2 Lecture Notes 18 Recursion s A function in C can make use of recursion: the function repeats an action by calling itself s Example: int factorial(int n) { if (n == 0) return(1); else return(n * factorial(n - 1)); } s Function factorial is called from within function factorial : this is a recursive call
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2 SFTW120 - Programming Science 3 Lecture Notes 18 Using recursion s Recursion is suitable for problems where: b One or more simple cases of the problem exist that have an easy, non-recursive solution b The other cases can be redefined in terms of problems that are closer to the simple cases b Redefining the problem repeatedly with each function call, the problem can be reduced to many simple cases which are easy to solve s Pseudocode: if this is a simple case solve it else redefine the problem using recursion SFTW120 - Programming Science 4 Lecture Notes 18 Recursion in factorial s To calculate the factorial
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

SFTW120-LectureNotes-18 - SFTW120 Programming Science...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online