SlideShare a Scribd company logo
 2000 Prentice Hall, Inc.
All rights reserved.
Lecture 5 - Recursion
 2000 Prentice Hall, Inc.
All rights reserved.
Ex. 1: The Handshake Problem
There are n people in a room. If each person
shakes hands once with every other person. What
is the total number h(n) of handshakes?
h(2) = 1
h(3) = h(2) + 2
h(4) = h(3) + 3
h(n) = h(n-1) + n-1
h(n): Sum of integer from 1 to n-1 = n(n-1) / 2
 2000 Prentice Hall, Inc.
All rights reserved.
Recursion
• In some problems, it may be natural to define the
problem in terms of the problem itself.
• Recursion is useful for problems that can be
represented by a simpler version of the same
problem.
 2000 Prentice Hall, Inc.
All rights reserved.
Chapter 7: Recursion 4
Recursive Thinking
• Recursion is:
– A problem-solving approach, that can ...
– Generate simple solutions to ...
– Certain kinds of problems that ...
– Would be difficult to solve in other ways
• Recursion splits a problem:
– Into one or more simpler versions of itself
 2000 Prentice Hall, Inc.
All rights reserved.
Chapter 7: Recursion 5
Recursive Thinking: The General
Approach
1. if problem is “small enough”
2. solve it directly
3. else
4. break into one or more smaller subproblems
5. solve each subproblem recursively
6. combine results into solution to whole problem
 2000 Prentice Hall, Inc.
All rights reserved.
Recursion
• Recursive functions
– Functions that call themselves
– Can only solve a base case
– Divide a problem up into
• What it can do
• What it cannot do
– What it cannot do resembles original problem
– The function launches a new copy of itself (recursion
step) to solve what it cannot do
– Eventually base case gets solved
• Gets plugged in, works its way up and solves whole problem
 2000 Prentice Hall, Inc.
All rights reserved.
Recursion
• Example: factorials
– 5! = 5 * 4 * 3 * 2 * 1
– Notice that
• 5! = 5 * 4!
• 4! = 4 * 3! ...
– Can compute factorials recursively
– Solve base case (1! = 0! = 1) then plug in
• 2! = 2 * 1! = 2 * 1 = 2;
• 3! = 3 * 2! = 3 * 2 = 6;
 2000 Prentice Hall, Inc.
All rights reserved.
Example Using Recursion: The Fibonacci
Series
• Fibonacci series: 0, 1, 1, 2, 3, 5, 8...
– Each number is the sum of the previous two
– Can be solved recursively:
• fib( n ) = fib( n - 1 ) + fib( n – 2 )
– Code for the fibaonacci function
long fibonacci( long n )
{
if (n == 0 || n == 1) // base case
return n;
else
return fibonacci( n - 1) +
fibonacci( n – 2 );
}
 2000 Prentice Hall, Inc.
All rights reserved.
Example Using Recursion: The Fibonacci
Series
• Set of recursive calls to function fibonacci
f( 3 )
f( 1 )
f( 2 )
f( 1 ) f( 0 ) return 1
return 1 return 0
return +
+
return
 2000 Prentice Hall, Inc.
All rights reserved.
Outline
Outline
1. Function prototype
1.1 Initialize variables
2. Input an integer
2.1 Call function
fibonacci
2.2 Output results.
3. Define fibonacci
recursively
Program Output
1 /* Fig. 5.15: fig05_15.c
2 Recursive fibonacci function */
3 #include <stdio.h>
4
5 long fibonacci( long );
6
7 int main()
8 {
9 long result, number;
10
11 printf( "Enter an integer: " );
12 scanf( "%ld", &number );
13 result = fibonacci( number );
14 printf( "Fibonacci( %ld ) = %ldn", number, result );
15 return 0;
16 }
17
18 /* Recursive definition of function fibonacci */
19 long fibonacci( long n )
20 {
21 if ( n == 0 || n == 1 )
22 return n;
23 else
24 return fibonacci( n - 1 ) + fibonacci( n - 2 );
25 }
Enter an integer: 0
Fibonacci(0) = 0
Enter an integer: 1
Fibonacci(1) = 1
 2000 Prentice Hall, Inc.
All rights reserved.
Outline
Outline
Program Output
Enter an integer: 2
Fibonacci(2) = 1
Enter an integer: 3
Fibonacci(3) = 2
Enter an integer: 4
Fibonacci(4) = 3
Enter an integer: 5
Fibonacci(5) = 5
Enter an integer: 6
Fibonacci(6) = 8
Enter an integer: 10
Fibonacci(10) = 55
Enter an integer: 20
Fibonacci(20) = 6765
Enter an integer: 30
Fibonacci(30) = 832040
Enter an integer: 35
Fibonacci(35) = 9227465
 2000 Prentice Hall, Inc.
All rights reserved.
Example: Exponential function
• How to write exp(int numb, int power) recursively?
int exp(int numb, int power){
if(power ==0)
return 1;
return numb * exp(numb, power -1);
}
 2000 Prentice Hall, Inc.
All rights reserved.
Recursion vs. Iteration
• Repetition
– Iteration: explicit loop
– Recursion: repeated function calls
• Termination
– Iteration: loop condition fails
– Recursion: base case recognized
• Both can have infinite loops
• Balance
– Choice between performance (iteration) and good software
engineering (recursion)

More Related Content

PDF
Recursion.pdf
PDF
Effective Algorithm for n Fibonacci Number By: Professor Lili Saghafi
PPT
14 recursion
PDF
Dynamic programing
PPT
Dynamicpgmming
PPTX
Dynamic programming Basics
PPTX
6-Python-Recursion PPT.pptx
PDF
Lecture 2.4 Recursion.pdf
Recursion.pdf
Effective Algorithm for n Fibonacci Number By: Professor Lili Saghafi
14 recursion
Dynamic programing
Dynamicpgmming
Dynamic programming Basics
6-Python-Recursion PPT.pptx
Lecture 2.4 Recursion.pdf

Similar to Recursion C programming exercises_ Recursion - w3resource.ppt (20)

PPTX
Recursion
PPTX
lecture4-recursion.pptx
DOCX
Write a recursive C++ function that inputs a nonnegative integer n an.docx
PPT
M251_Meeting 9 (Recursion_AdvancedJava).ppt
PPT
Dynamic pgmming
PDF
Fibonacci Function Gallery - Part 1 (of a series) - with minor corrections
PPTX
W8L1 Introduction & Fibonacci Numbers part 1.pptx
PPTX
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
PPT
dynamic programming Rod cutting class
PPTX
PPT
recursion based on koffmann and wolfgang
PPTX
Annotaed slides for dynamic programming algorithm
PPT
FUNDAMETAL ALG.ppt
PPTX
Python recursion
PPTX
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
PDF
chapter1.pdf ......................................
PPTX
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
PPTX
Exploring Tailrec Through Time Until Kotlin.pptx
PDF
12200224070_Adnan_Ahmed_DAAbhbhbh_63.pdf
Recursion
lecture4-recursion.pptx
Write a recursive C++ function that inputs a nonnegative integer n an.docx
M251_Meeting 9 (Recursion_AdvancedJava).ppt
Dynamic pgmming
Fibonacci Function Gallery - Part 1 (of a series) - with minor corrections
W8L1 Introduction & Fibonacci Numbers part 1.pptx
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
dynamic programming Rod cutting class
recursion based on koffmann and wolfgang
Annotaed slides for dynamic programming algorithm
FUNDAMETAL ALG.ppt
Python recursion
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
chapter1.pdf ......................................
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
Exploring Tailrec Through Time Until Kotlin.pptx
12200224070_Adnan_Ahmed_DAAbhbhbh_63.pdf
Ad

More from Carlos701746 (20)

PPTX
Module VII modified.pptxpresentation03.p
PPTX
MY PRESENTATION.pptxpresentation03.pptxm
PPTX
presentation03.pptxpresentation03.pptxpr
PPTX
CHAPTER 4 COMPUTER NETWORK FUNDAMENTAl.pptx.pptx
PPTX
CHAPTER 4 COMPUTER NETWORK FOR BUSINESS INFORMATION DISSEMINATION.pptx
PPTX
CHAPTER 4 COMPUTER NETWORK FOR BUSINESS INFORMATION DISSEMINATION.pptx
PPTX
Draw the flowchart of the above algorithm.pptx
PPTX
BUSINESS ETHICS IN COMPUTING FUNDAMENTALS .pptx
PPT
Professional Ethics Overview IN computing.ppt
PPTX
installingoperatingsy XP Installing Operating System.pptx
PPT
Topic 1 B C programming exercises one.ppt
PPT
Arrays in c programing. practicals and .ppt
PPTX
Transaction processing system in BICTPS.pptx
PPTX
MANAGEMENT INFORMATION SYSTEMS FOR MANAGEMENT DECISION MAKING.pptx
PPTX
USE COMPUTER FUNDAMETALS TO IDENTIFY TYPES AND FUNCTIONS OF A COMPUTER SOFTWA...
PPTX
Updated_Lighting_Device_Control_System.pptx
PPTX
Architecture Software Interface for students.pptx
PDF
KA 5 - Lecture 1 - Parallel Processing.pdf
PPTX
PPt Sets and Venn diagrams in discrete maths.pptx
PPTX
Part Four The CPU architecture in .pptx
Module VII modified.pptxpresentation03.p
MY PRESENTATION.pptxpresentation03.pptxm
presentation03.pptxpresentation03.pptxpr
CHAPTER 4 COMPUTER NETWORK FUNDAMENTAl.pptx.pptx
CHAPTER 4 COMPUTER NETWORK FOR BUSINESS INFORMATION DISSEMINATION.pptx
CHAPTER 4 COMPUTER NETWORK FOR BUSINESS INFORMATION DISSEMINATION.pptx
Draw the flowchart of the above algorithm.pptx
BUSINESS ETHICS IN COMPUTING FUNDAMENTALS .pptx
Professional Ethics Overview IN computing.ppt
installingoperatingsy XP Installing Operating System.pptx
Topic 1 B C programming exercises one.ppt
Arrays in c programing. practicals and .ppt
Transaction processing system in BICTPS.pptx
MANAGEMENT INFORMATION SYSTEMS FOR MANAGEMENT DECISION MAKING.pptx
USE COMPUTER FUNDAMETALS TO IDENTIFY TYPES AND FUNCTIONS OF A COMPUTER SOFTWA...
Updated_Lighting_Device_Control_System.pptx
Architecture Software Interface for students.pptx
KA 5 - Lecture 1 - Parallel Processing.pdf
PPt Sets and Venn diagrams in discrete maths.pptx
Part Four The CPU architecture in .pptx
Ad

Recently uploaded (20)

PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPT
Quality review (1)_presentation of this 21
PPTX
STUDY DESIGN details- Lt Col Maksud (21).pptx
PPTX
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
PPTX
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
PDF
Mega Projects Data Mega Projects Data
PPTX
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
PPT
Miokarditis (Inflamasi pada Otot Jantung)
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PDF
Foundation of Data Science unit number two notes
PDF
Fluorescence-microscope_Botany_detailed content
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PDF
annual-report-2024-2025 original latest.
PPTX
IBA_Chapter_11_Slides_Final_Accessible.pptx
PPTX
Acceptance and paychological effects of mandatory extra coach I classes.pptx
PPTX
Supervised vs unsupervised machine learning algorithms
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
PDF
.pdf is not working space design for the following data for the following dat...
PPTX
Data_Analytics_and_PowerBI_Presentation.pptx
Galatica Smart Energy Infrastructure Startup Pitch Deck
Quality review (1)_presentation of this 21
STUDY DESIGN details- Lt Col Maksud (21).pptx
The THESIS FINAL-DEFENSE-PRESENTATION.pptx
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
Mega Projects Data Mega Projects Data
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
Miokarditis (Inflamasi pada Otot Jantung)
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
Foundation of Data Science unit number two notes
Fluorescence-microscope_Botany_detailed content
Introduction-to-Cloud-ComputingFinal.pptx
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
annual-report-2024-2025 original latest.
IBA_Chapter_11_Slides_Final_Accessible.pptx
Acceptance and paychological effects of mandatory extra coach I classes.pptx
Supervised vs unsupervised machine learning algorithms
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
.pdf is not working space design for the following data for the following dat...
Data_Analytics_and_PowerBI_Presentation.pptx

Recursion C programming exercises_ Recursion - w3resource.ppt

  • 1.  2000 Prentice Hall, Inc. All rights reserved. Lecture 5 - Recursion
  • 2.  2000 Prentice Hall, Inc. All rights reserved. Ex. 1: The Handshake Problem There are n people in a room. If each person shakes hands once with every other person. What is the total number h(n) of handshakes? h(2) = 1 h(3) = h(2) + 2 h(4) = h(3) + 3 h(n) = h(n-1) + n-1 h(n): Sum of integer from 1 to n-1 = n(n-1) / 2
  • 3.  2000 Prentice Hall, Inc. All rights reserved. Recursion • In some problems, it may be natural to define the problem in terms of the problem itself. • Recursion is useful for problems that can be represented by a simpler version of the same problem.
  • 4.  2000 Prentice Hall, Inc. All rights reserved. Chapter 7: Recursion 4 Recursive Thinking • Recursion is: – A problem-solving approach, that can ... – Generate simple solutions to ... – Certain kinds of problems that ... – Would be difficult to solve in other ways • Recursion splits a problem: – Into one or more simpler versions of itself
  • 5.  2000 Prentice Hall, Inc. All rights reserved. Chapter 7: Recursion 5 Recursive Thinking: The General Approach 1. if problem is “small enough” 2. solve it directly 3. else 4. break into one or more smaller subproblems 5. solve each subproblem recursively 6. combine results into solution to whole problem
  • 6.  2000 Prentice Hall, Inc. All rights reserved. Recursion • Recursive functions – Functions that call themselves – Can only solve a base case – Divide a problem up into • What it can do • What it cannot do – What it cannot do resembles original problem – The function launches a new copy of itself (recursion step) to solve what it cannot do – Eventually base case gets solved • Gets plugged in, works its way up and solves whole problem
  • 7.  2000 Prentice Hall, Inc. All rights reserved. Recursion • Example: factorials – 5! = 5 * 4 * 3 * 2 * 1 – Notice that • 5! = 5 * 4! • 4! = 4 * 3! ... – Can compute factorials recursively – Solve base case (1! = 0! = 1) then plug in • 2! = 2 * 1! = 2 * 1 = 2; • 3! = 3 * 2! = 3 * 2 = 6;
  • 8.  2000 Prentice Hall, Inc. All rights reserved. Example Using Recursion: The Fibonacci Series • Fibonacci series: 0, 1, 1, 2, 3, 5, 8... – Each number is the sum of the previous two – Can be solved recursively: • fib( n ) = fib( n - 1 ) + fib( n – 2 ) – Code for the fibaonacci function long fibonacci( long n ) { if (n == 0 || n == 1) // base case return n; else return fibonacci( n - 1) + fibonacci( n – 2 ); }
  • 9.  2000 Prentice Hall, Inc. All rights reserved. Example Using Recursion: The Fibonacci Series • Set of recursive calls to function fibonacci f( 3 ) f( 1 ) f( 2 ) f( 1 ) f( 0 ) return 1 return 1 return 0 return + + return
  • 10.  2000 Prentice Hall, Inc. All rights reserved. Outline Outline 1. Function prototype 1.1 Initialize variables 2. Input an integer 2.1 Call function fibonacci 2.2 Output results. 3. Define fibonacci recursively Program Output 1 /* Fig. 5.15: fig05_15.c 2 Recursive fibonacci function */ 3 #include <stdio.h> 4 5 long fibonacci( long ); 6 7 int main() 8 { 9 long result, number; 10 11 printf( "Enter an integer: " ); 12 scanf( "%ld", &number ); 13 result = fibonacci( number ); 14 printf( "Fibonacci( %ld ) = %ldn", number, result ); 15 return 0; 16 } 17 18 /* Recursive definition of function fibonacci */ 19 long fibonacci( long n ) 20 { 21 if ( n == 0 || n == 1 ) 22 return n; 23 else 24 return fibonacci( n - 1 ) + fibonacci( n - 2 ); 25 } Enter an integer: 0 Fibonacci(0) = 0 Enter an integer: 1 Fibonacci(1) = 1
  • 11.  2000 Prentice Hall, Inc. All rights reserved. Outline Outline Program Output Enter an integer: 2 Fibonacci(2) = 1 Enter an integer: 3 Fibonacci(3) = 2 Enter an integer: 4 Fibonacci(4) = 3 Enter an integer: 5 Fibonacci(5) = 5 Enter an integer: 6 Fibonacci(6) = 8 Enter an integer: 10 Fibonacci(10) = 55 Enter an integer: 20 Fibonacci(20) = 6765 Enter an integer: 30 Fibonacci(30) = 832040 Enter an integer: 35 Fibonacci(35) = 9227465
  • 12.  2000 Prentice Hall, Inc. All rights reserved. Example: Exponential function • How to write exp(int numb, int power) recursively? int exp(int numb, int power){ if(power ==0) return 1; return numb * exp(numb, power -1); }
  • 13.  2000 Prentice Hall, Inc. All rights reserved. Recursion vs. Iteration • Repetition – Iteration: explicit loop – Recursion: repeated function calls • Termination – Iteration: loop condition fails – Recursion: base case recognized • Both can have infinite loops • Balance – Choice between performance (iteration) and good software engineering (recursion)