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

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

PPTX
Recursion
SAGARDAVE29
 
PPTX
lecture4-recursion.pptx
Lizhen Shi
 
DOCX
Write a recursive C++ function that inputs a nonnegative integer n an.docx
ajoy21
 
PPT
M251_Meeting 9 (Recursion_AdvancedJava).ppt
smartashammari
 
PPT
Dynamic pgmming
Dr. C.V. Suresh Babu
 
PDF
Fibonacci Function Gallery - Part 1 (of a series) - with minor corrections
Philip Schwarz
 
PPTX
W8L1 Introduction & Fibonacci Numbers part 1.pptx
sakibahmed181234
 
PPTX
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
Simplilearn
 
PPT
dynamic programming Rod cutting class
giridaroori
 
PPTX
Python.pptx
AKANSHAMITTAL2K21AFI
 
PPT
recursion based on koffmann and wolfgang
vidhyapm2
 
PPTX
Annotaed slides for dynamic programming algorithm
johnathangamal27
 
PPT
FUNDAMETAL ALG.ppt
Menaka Sivakumar
 
PPTX
Python recursion
ToniyaP1
 
PPTX
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
15AnasKhan
 
PDF
chapter1.pdf ......................................
nourhandardeer3
 
PPTX
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
usha raj
 
PPTX
Exploring Tailrec Through Time Until Kotlin.pptx
João Esperancinha
 
PDF
12200224070_Adnan_Ahmed_DAAbhbhbh_63.pdf
arijitghosal14
 
Recursion
SAGARDAVE29
 
lecture4-recursion.pptx
Lizhen Shi
 
Write a recursive C++ function that inputs a nonnegative integer n an.docx
ajoy21
 
M251_Meeting 9 (Recursion_AdvancedJava).ppt
smartashammari
 
Dynamic pgmming
Dr. C.V. Suresh Babu
 
Fibonacci Function Gallery - Part 1 (of a series) - with minor corrections
Philip Schwarz
 
W8L1 Introduction & Fibonacci Numbers part 1.pptx
sakibahmed181234
 
What Is Dynamic Programming? | Dynamic Programming Explained | Programming Fo...
Simplilearn
 
dynamic programming Rod cutting class
giridaroori
 
recursion based on koffmann and wolfgang
vidhyapm2
 
Annotaed slides for dynamic programming algorithm
johnathangamal27
 
FUNDAMETAL ALG.ppt
Menaka Sivakumar
 
Python recursion
ToniyaP1
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
15AnasKhan
 
chapter1.pdf ......................................
nourhandardeer3
 
6 Recursion Using Python 1.pptx6 Recursion Using Python 1.pptx
usha raj
 
Exploring Tailrec Through Time Until Kotlin.pptx
João Esperancinha
 
12200224070_Adnan_Ahmed_DAAbhbhbh_63.pdf
arijitghosal14
 

More from Carlos701746 (20)

PPTX
CHAPTER 4 COMPUTER NETWORK FOR BUSINESS INFORMATION DISSEMINATION.pptx
Carlos701746
 
PPTX
Draw the flowchart of the above algorithm.pptx
Carlos701746
 
PPTX
BUSINESS ETHICS IN COMPUTING FUNDAMENTALS .pptx
Carlos701746
 
PPT
Professional Ethics Overview IN computing.ppt
Carlos701746
 
PPTX
installingoperatingsy XP Installing Operating System.pptx
Carlos701746
 
PPT
Topic 1 B C programming exercises one.ppt
Carlos701746
 
PPT
Arrays in c programing. practicals and .ppt
Carlos701746
 
PPTX
Transaction processing system in BICTPS.pptx
Carlos701746
 
PPTX
MANAGEMENT INFORMATION SYSTEMS FOR MANAGEMENT DECISION MAKING.pptx
Carlos701746
 
PPTX
USE COMPUTER FUNDAMETALS TO IDENTIFY TYPES AND FUNCTIONS OF A COMPUTER SOFTWA...
Carlos701746
 
PPTX
Updated_Lighting_Device_Control_System.pptx
Carlos701746
 
PPTX
Architecture Software Interface for students.pptx
Carlos701746
 
PDF
KA 5 - Lecture 1 - Parallel Processing.pdf
Carlos701746
 
PPTX
PPt Sets and Venn diagrams in discrete maths.pptx
Carlos701746
 
PPTX
Part Four The CPU architecture in .pptx
Carlos701746
 
PDF
OIT 116 LOOPS AND CONDITION STATEMENTS.pdf
Carlos701746
 
PPT
OIT 116 - Lecture 3_2 Arrays, Pointers and Strings (1) (1).ppt
Carlos701746
 
PPTX
IT Ethical Practices and Compliance.pptx
Carlos701746
 
PPTX
Network_Protocals in IT fundamentals .pptx
Carlos701746
 
PPTX
ARTHEMATIC OPERATIONS IN C PROGRAMING.pptx
Carlos701746
 
CHAPTER 4 COMPUTER NETWORK FOR BUSINESS INFORMATION DISSEMINATION.pptx
Carlos701746
 
Draw the flowchart of the above algorithm.pptx
Carlos701746
 
BUSINESS ETHICS IN COMPUTING FUNDAMENTALS .pptx
Carlos701746
 
Professional Ethics Overview IN computing.ppt
Carlos701746
 
installingoperatingsy XP Installing Operating System.pptx
Carlos701746
 
Topic 1 B C programming exercises one.ppt
Carlos701746
 
Arrays in c programing. practicals and .ppt
Carlos701746
 
Transaction processing system in BICTPS.pptx
Carlos701746
 
MANAGEMENT INFORMATION SYSTEMS FOR MANAGEMENT DECISION MAKING.pptx
Carlos701746
 
USE COMPUTER FUNDAMETALS TO IDENTIFY TYPES AND FUNCTIONS OF A COMPUTER SOFTWA...
Carlos701746
 
Updated_Lighting_Device_Control_System.pptx
Carlos701746
 
Architecture Software Interface for students.pptx
Carlos701746
 
KA 5 - Lecture 1 - Parallel Processing.pdf
Carlos701746
 
PPt Sets and Venn diagrams in discrete maths.pptx
Carlos701746
 
Part Four The CPU architecture in .pptx
Carlos701746
 
OIT 116 LOOPS AND CONDITION STATEMENTS.pdf
Carlos701746
 
OIT 116 - Lecture 3_2 Arrays, Pointers and Strings (1) (1).ppt
Carlos701746
 
IT Ethical Practices and Compliance.pptx
Carlos701746
 
Network_Protocals in IT fundamentals .pptx
Carlos701746
 
ARTHEMATIC OPERATIONS IN C PROGRAMING.pptx
Carlos701746
 
Ad

Recently uploaded (20)

PPTX
Human-Action-Recognition-Understanding-Behavior.pptx
nreddyjanga
 
PPTX
TSM_08_0811111111111111111111111111111111111111111111111
csomonasteriomoscow
 
PPTX
Resmed Rady Landis May 4th - analytics.pptx
Adrian Limanto
 
PPTX
AI Project Cycle and Ethical Frameworks.pptx
RiddhimaVarshney1
 
PDF
Choosing the Right Database for Indexing.pdf
Tamanna
 
PPTX
Rocket-Launched-PowerPoint-Template.pptx
Arden31
 
PDF
R Cookbook - Processing and Manipulating Geological spatial data with R.pdf
OtnielSimopiaref2
 
DOC
MATRIX_AMAN IRAWAN_20227479046.docbbbnnb
vanitafiani1
 
PPTX
apidays Munich 2025 - Building an AWS Serverless Application with Terraform, ...
apidays
 
DOCX
AI/ML Applications in Financial domain projects
Rituparna De
 
PDF
MusicVideoProjectRubric Animation production music video.pdf
ALBERTIANCASUGA
 
PDF
How to Avoid 7 Costly Mainframe Migration Mistakes
JP Infra Pvt Ltd
 
PDF
Avatar for apidays apidays PRO June 07, 2025 0 5 apidays Helsinki & North 2...
apidays
 
PPTX
recruitment Presentation.pptxhdhshhshshhehh
devraj40467
 
PPTX
DATA-COLLECTION METHODS, TYPES AND SOURCES
biggdaad011
 
PDF
Performance Report Sample (Draft7).pdf
AmgadMaher5
 
PPTX
Exploring Multilingual Embeddings for Italian Semantic Search: A Pretrained a...
Sease
 
PPTX
Numbers of a nation: how we estimate population statistics | Accessible slides
Office for National Statistics
 
PPTX
Introduction to Artificial Intelligence.pptx
StarToon1
 
PPT
Data base management system Transactions.ppt
gandhamcharan2006
 
Human-Action-Recognition-Understanding-Behavior.pptx
nreddyjanga
 
TSM_08_0811111111111111111111111111111111111111111111111
csomonasteriomoscow
 
Resmed Rady Landis May 4th - analytics.pptx
Adrian Limanto
 
AI Project Cycle and Ethical Frameworks.pptx
RiddhimaVarshney1
 
Choosing the Right Database for Indexing.pdf
Tamanna
 
Rocket-Launched-PowerPoint-Template.pptx
Arden31
 
R Cookbook - Processing and Manipulating Geological spatial data with R.pdf
OtnielSimopiaref2
 
MATRIX_AMAN IRAWAN_20227479046.docbbbnnb
vanitafiani1
 
apidays Munich 2025 - Building an AWS Serverless Application with Terraform, ...
apidays
 
AI/ML Applications in Financial domain projects
Rituparna De
 
MusicVideoProjectRubric Animation production music video.pdf
ALBERTIANCASUGA
 
How to Avoid 7 Costly Mainframe Migration Mistakes
JP Infra Pvt Ltd
 
Avatar for apidays apidays PRO June 07, 2025 0 5 apidays Helsinki & North 2...
apidays
 
recruitment Presentation.pptxhdhshhshshhehh
devraj40467
 
DATA-COLLECTION METHODS, TYPES AND SOURCES
biggdaad011
 
Performance Report Sample (Draft7).pdf
AmgadMaher5
 
Exploring Multilingual Embeddings for Italian Semantic Search: A Pretrained a...
Sease
 
Numbers of a nation: how we estimate population statistics | Accessible slides
Office for National Statistics
 
Introduction to Artificial Intelligence.pptx
StarToon1
 
Data base management system Transactions.ppt
gandhamcharan2006
 
Ad

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)