SlideShare a Scribd company logo
1 of 2
Download to read offline
Recursion Examples:
1. Factorial
2. Binary representation
1. Calculating Factorial of a Number:
factorial function(n!): the product of the integers between 1 and n.
In other words multiply all whole numbers from our chosen number down to 1.
➢ Code:
Using Loop Using Recursion
int main()
{
int num;cin >> num;
int factorial = 1;
for (int i = 1; i <= num; ++i)factorial *=
i;
cout << factorial;
return 0;
}
int factorial(int num) {
if (num == 0)return 1;
else return num * factorial(num - 1);
}
int main()
{
int num;cin >> num;
cout << factorial(num);
return 0;
}
➢ Behind the scenes:
n!=n*(n-1)!
4! = 4 × 3 × 2 × 1 = 24
1! = 1
int factorial(int 3)
{
if (0 == 0)return 1;
else
return0*factorial(-
1);
}
num =0
int factorial(int 3)
{
if (1 == 0)return 1;
else
return1*factorial(0);
}
num =1
int factorial(int 3)
{
if (2 == 0)return 1;
else
return2*factorial(1);
}
num =2
int factorial(int 3)
{
if (3 == 0)return 1;
else
return3*factorial(2);
}
num=3
int factorial(int 4)
{
if (4 == 0)return 1;
else
return4*factorial(3);
}
num =4
Key :
Red: False -Not executed
Green: True - Executed
 Important Note:
when a function calls itself, a new copy of that function is run. The local variables in the second version are
independent of the local variables in the first, and they cannot affect one another directly.
➢ Steps:
1. Identify the basic cases (those in which the subprogram can solve the problem directly without recurring to
recursive calls) and determine how they are solved.
For example, in the case of factorial, the only basic case used in the function is n=0. Similarly, we could have
considered a more general basic case (e.g., n ≤ 1). In both cases, the function should return 1.
2. Determine how to resolve the non-basic cases in terms of the basic cases, which we assume we can already
solve.
In the case of a factorial, we know that the factorial of a number n greater than zero is n*factorial(n-1).
3. Make sure that the parameters of the call move closer to the basic cases at each recursive call. This should
guarantee a finite sequence of recursive calls that always terminates.
In the case of a factorial, n-1 is closer to 0 than n. Therefore, we can guarantee that this function terminates.
2. Writing Binary Representation of a Number:
➢ Code
Using Loop Using Recursion
int binary[32];
int main()
{
int num;cin >> num;
int i = 0;
for (; 0 < num; ++i) {
binary[i] = num % 2;
num /= 2;
}
for (int j = i - 1; j >= 0; j--) {
cout << binary[j];
}
return 0;
}
void binary(int num)
{
if (num == 1) cout << 1;
else {
binary(num / 2);
cout << num % 2;
}
}
int main()
{
int num; cin >> num;
binary(num);
return 0;
}
1
3*2=6
1*2=2
1*1=1
4*6=24
4!= 4*3!
3!=3*2!
2!=2*1!
1!=1*0!
0!=1

More Related Content

What's hot

3.2 Derivative as a Function
3.2 Derivative as a Function3.2 Derivative as a Function
3.2 Derivative as a Function
gregcross22
 
Bti1022 lab sheet 9 10
Bti1022 lab sheet 9 10Bti1022 lab sheet 9 10
Bti1022 lab sheet 9 10
alish sha
 

What's hot (11)

Python Conditionals and Functions
Python Conditionals and FunctionsPython Conditionals and Functions
Python Conditionals and Functions
 
Pointers lesson 4 (malloc and its use)
Pointers lesson 4 (malloc and its use)Pointers lesson 4 (malloc and its use)
Pointers lesson 4 (malloc and its use)
 
R normal distribution
R   normal distributionR   normal distribution
R normal distribution
 
Builtin Functions and variables naming rules
Builtin Functions and variables naming rulesBuiltin Functions and variables naming rules
Builtin Functions and variables naming rules
 
3.2 Derivative as a Function
3.2 Derivative as a Function3.2 Derivative as a Function
3.2 Derivative as a Function
 
Basic python programs
Basic python programsBasic python programs
Basic python programs
 
Bti1022 lab sheet 9 10
Bti1022 lab sheet 9 10Bti1022 lab sheet 9 10
Bti1022 lab sheet 9 10
 
Check box, image
Check box, imageCheck box, image
Check box, image
 
Pointer example
Pointer examplePointer example
Pointer example
 
Mac Interview Workshop 2021
Mac Interview Workshop 2021Mac Interview Workshop 2021
Mac Interview Workshop 2021
 
Matlab numbers
Matlab numbersMatlab numbers
Matlab numbers
 

Similar to Recursion examples

1- please please please don't send me an incomplete program this code.docx
1- please please please don't send me an incomplete program this code.docx1- please please please don't send me an incomplete program this code.docx
1- please please please don't send me an incomplete program this code.docx
EvandWyBurgesss
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
15AnasKhan
 

Similar to Recursion examples (20)

Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
Recurrence relationships
Recurrence relationshipsRecurrence relationships
Recurrence relationships
 
1 chapter1 introduction
1 chapter1 introduction1 chapter1 introduction
1 chapter1 introduction
 
tutorial5.ppt
tutorial5.ppttutorial5.ppt
tutorial5.ppt
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
1- please please please don't send me an incomplete program this code.docx
1- please please please don't send me an incomplete program this code.docx1- please please please don't send me an incomplete program this code.docx
1- please please please don't send me an incomplete program this code.docx
 
Introduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptxIntroduction to Dynamic Programming.pptx
Introduction to Dynamic Programming.pptx
 
algo_vc_lecture8.ppt
algo_vc_lecture8.pptalgo_vc_lecture8.ppt
algo_vc_lecture8.ppt
 
Unit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfUnit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdf
 
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS - SARASWATHI RAMALINGAM
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS  - SARASWATHI RAMALINGAMPROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS  - SARASWATHI RAMALINGAM
PROGRAMMING IN C EXAMPLE PROGRAMS FOR NEW LEARNERS - SARASWATHI RAMALINGAM
 
algorithm Unit 2
algorithm Unit 2 algorithm Unit 2
algorithm Unit 2
 
Unit 2 in daa
Unit 2 in daaUnit 2 in daa
Unit 2 in daa
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
Daa notes 2
Daa notes 2Daa notes 2
Daa notes 2
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questions
 
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
35000120060_Nitesh Modi_CSE Presentation on recursion.pptx
 
3.pdf
3.pdf3.pdf
3.pdf
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
21221
2122121221
21221
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1
 

Recently uploaded

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
SoniaTolstoy
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 

Recently uploaded (20)

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Recursion examples

  • 1. Recursion Examples: 1. Factorial 2. Binary representation 1. Calculating Factorial of a Number: factorial function(n!): the product of the integers between 1 and n. In other words multiply all whole numbers from our chosen number down to 1. ➢ Code: Using Loop Using Recursion int main() { int num;cin >> num; int factorial = 1; for (int i = 1; i <= num; ++i)factorial *= i; cout << factorial; return 0; } int factorial(int num) { if (num == 0)return 1; else return num * factorial(num - 1); } int main() { int num;cin >> num; cout << factorial(num); return 0; } ➢ Behind the scenes: n!=n*(n-1)! 4! = 4 × 3 × 2 × 1 = 24 1! = 1 int factorial(int 3) { if (0 == 0)return 1; else return0*factorial(- 1); } num =0 int factorial(int 3) { if (1 == 0)return 1; else return1*factorial(0); } num =1 int factorial(int 3) { if (2 == 0)return 1; else return2*factorial(1); } num =2 int factorial(int 3) { if (3 == 0)return 1; else return3*factorial(2); } num=3 int factorial(int 4) { if (4 == 0)return 1; else return4*factorial(3); } num =4 Key : Red: False -Not executed Green: True - Executed
  • 2.  Important Note: when a function calls itself, a new copy of that function is run. The local variables in the second version are independent of the local variables in the first, and they cannot affect one another directly. ➢ Steps: 1. Identify the basic cases (those in which the subprogram can solve the problem directly without recurring to recursive calls) and determine how they are solved. For example, in the case of factorial, the only basic case used in the function is n=0. Similarly, we could have considered a more general basic case (e.g., n ≤ 1). In both cases, the function should return 1. 2. Determine how to resolve the non-basic cases in terms of the basic cases, which we assume we can already solve. In the case of a factorial, we know that the factorial of a number n greater than zero is n*factorial(n-1). 3. Make sure that the parameters of the call move closer to the basic cases at each recursive call. This should guarantee a finite sequence of recursive calls that always terminates. In the case of a factorial, n-1 is closer to 0 than n. Therefore, we can guarantee that this function terminates. 2. Writing Binary Representation of a Number: ➢ Code Using Loop Using Recursion int binary[32]; int main() { int num;cin >> num; int i = 0; for (; 0 < num; ++i) { binary[i] = num % 2; num /= 2; } for (int j = i - 1; j >= 0; j--) { cout << binary[j]; } return 0; } void binary(int num) { if (num == 1) cout << 1; else { binary(num / 2); cout << num % 2; } } int main() { int num; cin >> num; binary(num); return 0; } 1 3*2=6 1*2=2 1*1=1 4*6=24 4!= 4*3! 3!=3*2! 2!=2*1! 1!=1*0! 0!=1