SlideShare a Scribd company logo
Recursion, Debugging
Saule Anay
Fall 2016, NU, CSCI 151
You should know already
• Functions
• Function parameters and arguments
• How to call function
• Global vs local variables
Today in the class
1. Recursion:
1. What is it?
2. How to use?
3. Examples
4. Recursion vs iteration
2. Inside my program
3. Debugging
1. what is it?
2. why we need?
3. How to use?
4. Examples.
4. Compiler errors
Recursion
• is a method where the solution to a problem
depends on solutions to smaller instances of
the same problem.
example: 2^11 = 2^10 * 2 = 1024 * 2
• one of the central ideas of computer science.
How do you empty a vase containing
five flowers?
Answer: if the vase is not empty, you take out one
flower and then you empty a vase containing four
flowers.
How do you empty a vase containing four flowers?
Answer: if the vase is not empty, you take out one
flower and then you empty a vase containing three
flowers.
…
How do you empty a vase containing one flower?
Answer: if the vase is not empty, you take out one
flower and then you empty a vase containing no
flowers.
How do you empty a vase containing no flowers?
Answer: if the vase is not empty, you take out one
flower but the vase is empty so you're done.
Base cases vs recursive cases
• one or more base cases:
– input(s) for which the function produces a result
trivially (without recurring),
– Base case for emptyVase: vase with zero flowers
• one or more recursive cases: input(s) for
which the program recurs (calls itself).
Example: vase with flowers bigger than zero.
How do you empty a vase containing
five flowers?
• Base: if Flowers=0  done. Vase is empty
• Recursive case: for all flowers>0, take out one
flower, empty Vase of (N-1) flowers
emptyVase program code
1. #include <stdio.h>
2. void emptyVase(int numFlowers){
3. if (numFlowers ==0){
4. printf("Vase is empty nown");
5. return;
6. }
7. if (numFlowers>0){
8. numFlowers--;
9. printf("one flower have been taken outn");
10. emptyVase(numFlowers);
11. } //end of IF statement
12. } //end of Function
13. int main () {
14. setvbuf(stdout, NULL, _IONBF, 0);
15. Int flowers =8;
16. emptyVase(flowers);
17. return 0;
18. }
Examples of recursive solution
1. Factorial:
Base case:0! = 1
Recursive case: for all n > 0, n! = n(n − 1)!
2. fibbonachi:
Base case:Fn(1) = 1, Fn(2) = 1
Recursive case: for all n > 2, Fn(n) = Fn(n-
1)+Fn(n-2)
3. X^n (x to the power n)
Base case: if n=0, x^n=1
Recursive case: for all n>0, x^n=x*x^(n-1)
Example with Factorial
Factorial recursive function
1. #include <stdio.h>
2. int factorial(int n){
3. //base case
4. if (n==0)
5. return 1;
6. //recursive case
7. if (n>0)
8. return n*factorial(n-1);
9. //default case if n<0
10. return -1;
11. } //end Factorial
12. int main () {
13. setvbuf(stdout, NULL, _IONBF, 0);
14. int number=8;
15. printf("fatorial of %i is %i n", number, factorial(number));
16. return 1;
17. }
Factorial iterative function
• #include <stdio.h>
• int factorial(int n){
• int i;
• int res=1;
• for(i=1; i<=n; i++)
• res=res*i;
• return res;
• } //end Factorial
• int main () {
• setvbuf(stdout, NULL, _IONBF, 0);
• int number=8;
• printf("fatorial of %i is %i n", number, factorial(number));
• return 1;
• }
Check list recursive function
• Have a base case
• Function call itself (recursive call)
• Recursive call MUST be with different input,
so that the base case must be reached
eventually
Recursion vs iteration
• Similarity
– Both repeat block of codes
• Difference
– iteration: loops to repeat the block of code
– recursion: call itself to repeat the block of code
Temination:
iteration: loop condition
recursion: base case
Infinite execution:
iteration: never reach loop condition
recursion: never reach base case
Which is better?
• It depends from situation:
– Some problem difficult to solve iteratively
– Some problem difficult to solve recursively
• Math people like recursion
– Shorter solution, abstraction
– To find good recursive solution is not always simple.
• CS people like iteration
– Easier to construct
– Easier to iterate and simulate (less magical)
Phillips head vs flat head screwdriver:
which is better?
It depends from situation
iterationrecursion
conclusion
• How to know if function recursive?
– It must call itself
• Recursive function must have 2 cases:
– Base case
– Recursive case
• Any recursion can be rewritten with iteration
• Which to choose depends on situation
What is inside my program?
Computer memory
What happens when?
1. you declare new variable?
2. You declare new array
3. You call a function
Computer allocates memory for variable, fro
array
function name var name value
continue
line console
main flowers 8 29
emptyVase(8) numFlowers 7 12
one flower have been taken
out
emptyVase(7) numFlowers 6 12
one flower have been taken
out
emptyVase(6) numFlowers 5 12
one flower have been taken
out
emptyVase(5) numFlowers 4 12
one flower have been taken
out
emptyVase(4) numFlowers 3 12
one flower have been taken
out
emptyVase(3) numFlowers 2 12
one flower have been taken
out
emptyVase(2) numFlowers 1 12
one flower have been taken
out
emptyVase(1) numFlowers 0 12
one flower have been taken
out
emptyVase(0) numFlowers 0 vase is empty
debugging
1. Debugging
1. what is it?
2. why we need?
3. How to use?
4. Examples.
What is debugging?
Debugging is the process of finding and resolving of
errors in the code that prevent correct operation
of program or computer software.
• To debug a program means:
1. find problem
2. isolate problematic part of code
3. fix it.
Finding error with testing
• Testing:
– Give minimum input value
– Give maximum input value
– Give as much as possible diverse input value
Example:
find maximum in the array
time advancer problem
Finding errors by debugging
• When Output is incorrect, it is difficult to find an
error.
• What is wrong? How to find an error?
• Debugging:
1. Print debugging
1. Add Printf statements in code, to check internal states of
the program
2. Use debugging tool
1. Eclipse has one
Debugging tool
1. Running program Step-by-step
2. Stopping(Pausing) program at some instruction.
And see current program state(breakpoints)
3. Modify program state (modify the values of the
variables) while it is running
What is the bug?
• “I’ve debugged a program”
• “Worked the bugs out”
• I fixed the problem, that bugs no longer exist
in my program
Debugging perspective in Eclipse
Debugging perspective in Eclipse
Problem with perspective? Reset it
Control of debugging
• F5 – step into
• F6 – step over
• F7 – step return
• Ctrl+F2 (red square) - terminate
When you return from emptyVase(7)
continue from this place: Line 13
Debugging of Carrot problem
• int main () {
• setvbuf(stdout, NULL, _IONBF, 0);
• int rabbits[5];
• int carrots=1;
• int i;
• for (i=0; i<6; i++){
• rabbits[i]=carrots;
• carrots+=3;
• if (carrots>=16)
• carrots=1;
• }
• for (i=0; i<6; i++)
• Printf(“%i, ”, rabbits[i]);
• return 0;
• }
Compiler errors
Compiler errors
4 Errors in Line 29
1 Warning in line 27.
Error in Line 29 fixing: replace
comas with semicolons

More Related Content

Viewers also liked

Recursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, BangaloreRecursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, Bangalore
Bhasker Kode
 
1392741020 traverse survey
1392741020 traverse survey1392741020 traverse survey
1392741020 traverse survey
anjali adabala
 
Programming in c
Programming in cProgramming in c
Programming in c
indra Kishor
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
avikdhupar
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
Deep C
Deep CDeep C
Deep C
Olve Maudal
 

Viewers also liked (6)

Recursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, BangaloreRecursion & Erlang, FunctionalConf 14, Bangalore
Recursion & Erlang, FunctionalConf 14, Bangalore
 
1392741020 traverse survey
1392741020 traverse survey1392741020 traverse survey
1392741020 traverse survey
 
Programming in c
Programming in cProgramming in c
Programming in c
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
 
Deep C
Deep CDeep C
Deep C
 

Similar to Recursion, debugging in c

CPP10 - Debugging
CPP10 - DebuggingCPP10 - Debugging
CPP10 - Debugging
Michael Heron
 
Lecture6 data structure(algorithms)
Lecture6 data structure(algorithms)Lecture6 data structure(algorithms)
Algorithms and how to write an algorithms
Algorithms and how to write an algorithmsAlgorithms and how to write an algorithms
Algorithms and how to write an algorithms
Ahmed Nobi
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
203318pmpc
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Wen-Tien Chang
 
CC-112-Lec.1.ppsx
CC-112-Lec.1.ppsxCC-112-Lec.1.ppsx
CC-112-Lec.1.ppsx
Aamir Shahzad
 
Code smells in PHP
Code smells in PHPCode smells in PHP
Code smells in PHP
Dagfinn Reiersøl
 
Programs_Problem_Solving_Algorithms.ppt
Programs_Problem_Solving_Algorithms.pptPrograms_Problem_Solving_Algorithms.ppt
Programs_Problem_Solving_Algorithms.ppt
malik681299
 
Week 1
Week 1Week 1
Week 1
EasyStudy3
 
Prompt-Engineering-Lecture-Elvis learn prompt engineering
Prompt-Engineering-Lecture-Elvis learn prompt engineeringPrompt-Engineering-Lecture-Elvis learn prompt engineering
Prompt-Engineering-Lecture-Elvis learn prompt engineering
SaweraKhadium
 
powerpoint 1-19.pdf
powerpoint 1-19.pdfpowerpoint 1-19.pdf
powerpoint 1-19.pdf
JuanPicasso7
 
part_1 (1).ppt
part_1 (1).pptpart_1 (1).ppt
part_1 (1).ppt
lekha572836
 
Python recursion
Python recursionPython recursion
Python recursion
Prof. Dr. K. Adisesha
 
Cis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingCis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programming
Hamad Odhabi
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
Andres Mendez-Vazquez
 
Case Study of the Unexplained
Case Study of the UnexplainedCase Study of the Unexplained
Case Study of the Unexplained
shannomc
 
Algorithm and flowchart with pseudo code
Algorithm and flowchart with pseudo codeAlgorithm and flowchart with pseudo code
Algorithm and flowchart with pseudo code
hamza javed
 
Lec 01 introduction
Lec 01   introductionLec 01   introduction
Lec 01 introduction
UmairMuzaffar9
 
Test-Driven Development
 Test-Driven Development  Test-Driven Development
Test-Driven Development
Amir Assad
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
VAIBHAVKADAGANCHI
 

Similar to Recursion, debugging in c (20)

CPP10 - Debugging
CPP10 - DebuggingCPP10 - Debugging
CPP10 - Debugging
 
Lecture6 data structure(algorithms)
Lecture6 data structure(algorithms)Lecture6 data structure(algorithms)
Lecture6 data structure(algorithms)
 
Algorithms and how to write an algorithms
Algorithms and how to write an algorithmsAlgorithms and how to write an algorithms
Algorithms and how to write an algorithms
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)Exception Handling: Designing Robust Software in Ruby (with presentation note)
Exception Handling: Designing Robust Software in Ruby (with presentation note)
 
CC-112-Lec.1.ppsx
CC-112-Lec.1.ppsxCC-112-Lec.1.ppsx
CC-112-Lec.1.ppsx
 
Code smells in PHP
Code smells in PHPCode smells in PHP
Code smells in PHP
 
Programs_Problem_Solving_Algorithms.ppt
Programs_Problem_Solving_Algorithms.pptPrograms_Problem_Solving_Algorithms.ppt
Programs_Problem_Solving_Algorithms.ppt
 
Week 1
Week 1Week 1
Week 1
 
Prompt-Engineering-Lecture-Elvis learn prompt engineering
Prompt-Engineering-Lecture-Elvis learn prompt engineeringPrompt-Engineering-Lecture-Elvis learn prompt engineering
Prompt-Engineering-Lecture-Elvis learn prompt engineering
 
powerpoint 1-19.pdf
powerpoint 1-19.pdfpowerpoint 1-19.pdf
powerpoint 1-19.pdf
 
part_1 (1).ppt
part_1 (1).pptpart_1 (1).ppt
part_1 (1).ppt
 
Python recursion
Python recursionPython recursion
Python recursion
 
Cis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingCis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programming
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
 
Case Study of the Unexplained
Case Study of the UnexplainedCase Study of the Unexplained
Case Study of the Unexplained
 
Algorithm and flowchart with pseudo code
Algorithm and flowchart with pseudo codeAlgorithm and flowchart with pseudo code
Algorithm and flowchart with pseudo code
 
Lec 01 introduction
Lec 01   introductionLec 01   introduction
Lec 01 introduction
 
Test-Driven Development
 Test-Driven Development  Test-Driven Development
Test-Driven Development
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 

Recently uploaded

Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 

Recently uploaded (20)

Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 

Recursion, debugging in c

  • 2. You should know already • Functions • Function parameters and arguments • How to call function • Global vs local variables
  • 3. Today in the class 1. Recursion: 1. What is it? 2. How to use? 3. Examples 4. Recursion vs iteration 2. Inside my program 3. Debugging 1. what is it? 2. why we need? 3. How to use? 4. Examples. 4. Compiler errors
  • 4. Recursion • is a method where the solution to a problem depends on solutions to smaller instances of the same problem. example: 2^11 = 2^10 * 2 = 1024 * 2 • one of the central ideas of computer science.
  • 5. How do you empty a vase containing five flowers? Answer: if the vase is not empty, you take out one flower and then you empty a vase containing four flowers. How do you empty a vase containing four flowers? Answer: if the vase is not empty, you take out one flower and then you empty a vase containing three flowers. … How do you empty a vase containing one flower? Answer: if the vase is not empty, you take out one flower and then you empty a vase containing no flowers. How do you empty a vase containing no flowers? Answer: if the vase is not empty, you take out one flower but the vase is empty so you're done.
  • 6. Base cases vs recursive cases • one or more base cases: – input(s) for which the function produces a result trivially (without recurring), – Base case for emptyVase: vase with zero flowers • one or more recursive cases: input(s) for which the program recurs (calls itself). Example: vase with flowers bigger than zero.
  • 7. How do you empty a vase containing five flowers? • Base: if Flowers=0  done. Vase is empty • Recursive case: for all flowers>0, take out one flower, empty Vase of (N-1) flowers
  • 8. emptyVase program code 1. #include <stdio.h> 2. void emptyVase(int numFlowers){ 3. if (numFlowers ==0){ 4. printf("Vase is empty nown"); 5. return; 6. } 7. if (numFlowers>0){ 8. numFlowers--; 9. printf("one flower have been taken outn"); 10. emptyVase(numFlowers); 11. } //end of IF statement 12. } //end of Function 13. int main () { 14. setvbuf(stdout, NULL, _IONBF, 0); 15. Int flowers =8; 16. emptyVase(flowers); 17. return 0; 18. }
  • 9. Examples of recursive solution 1. Factorial: Base case:0! = 1 Recursive case: for all n > 0, n! = n(n − 1)! 2. fibbonachi: Base case:Fn(1) = 1, Fn(2) = 1 Recursive case: for all n > 2, Fn(n) = Fn(n- 1)+Fn(n-2) 3. X^n (x to the power n) Base case: if n=0, x^n=1 Recursive case: for all n>0, x^n=x*x^(n-1)
  • 11. Factorial recursive function 1. #include <stdio.h> 2. int factorial(int n){ 3. //base case 4. if (n==0) 5. return 1; 6. //recursive case 7. if (n>0) 8. return n*factorial(n-1); 9. //default case if n<0 10. return -1; 11. } //end Factorial 12. int main () { 13. setvbuf(stdout, NULL, _IONBF, 0); 14. int number=8; 15. printf("fatorial of %i is %i n", number, factorial(number)); 16. return 1; 17. }
  • 12. Factorial iterative function • #include <stdio.h> • int factorial(int n){ • int i; • int res=1; • for(i=1; i<=n; i++) • res=res*i; • return res; • } //end Factorial • int main () { • setvbuf(stdout, NULL, _IONBF, 0); • int number=8; • printf("fatorial of %i is %i n", number, factorial(number)); • return 1; • }
  • 13. Check list recursive function • Have a base case • Function call itself (recursive call) • Recursive call MUST be with different input, so that the base case must be reached eventually
  • 14. Recursion vs iteration • Similarity – Both repeat block of codes • Difference – iteration: loops to repeat the block of code – recursion: call itself to repeat the block of code Temination: iteration: loop condition recursion: base case Infinite execution: iteration: never reach loop condition recursion: never reach base case
  • 15. Which is better? • It depends from situation: – Some problem difficult to solve iteratively – Some problem difficult to solve recursively • Math people like recursion – Shorter solution, abstraction – To find good recursive solution is not always simple. • CS people like iteration – Easier to construct – Easier to iterate and simulate (less magical)
  • 16. Phillips head vs flat head screwdriver: which is better? It depends from situation iterationrecursion
  • 17. conclusion • How to know if function recursive? – It must call itself • Recursive function must have 2 cases: – Base case – Recursive case • Any recursion can be rewritten with iteration • Which to choose depends on situation
  • 18. What is inside my program? Computer memory
  • 19. What happens when? 1. you declare new variable? 2. You declare new array 3. You call a function Computer allocates memory for variable, fro array
  • 20. function name var name value continue line console main flowers 8 29 emptyVase(8) numFlowers 7 12 one flower have been taken out emptyVase(7) numFlowers 6 12 one flower have been taken out emptyVase(6) numFlowers 5 12 one flower have been taken out emptyVase(5) numFlowers 4 12 one flower have been taken out emptyVase(4) numFlowers 3 12 one flower have been taken out emptyVase(3) numFlowers 2 12 one flower have been taken out emptyVase(2) numFlowers 1 12 one flower have been taken out emptyVase(1) numFlowers 0 12 one flower have been taken out emptyVase(0) numFlowers 0 vase is empty
  • 22. 1. Debugging 1. what is it? 2. why we need? 3. How to use? 4. Examples.
  • 23. What is debugging? Debugging is the process of finding and resolving of errors in the code that prevent correct operation of program or computer software. • To debug a program means: 1. find problem 2. isolate problematic part of code 3. fix it.
  • 24. Finding error with testing • Testing: – Give minimum input value – Give maximum input value – Give as much as possible diverse input value Example: find maximum in the array time advancer problem
  • 25. Finding errors by debugging • When Output is incorrect, it is difficult to find an error. • What is wrong? How to find an error? • Debugging: 1. Print debugging 1. Add Printf statements in code, to check internal states of the program 2. Use debugging tool 1. Eclipse has one
  • 26. Debugging tool 1. Running program Step-by-step 2. Stopping(Pausing) program at some instruction. And see current program state(breakpoints) 3. Modify program state (modify the values of the variables) while it is running
  • 27. What is the bug? • “I’ve debugged a program” • “Worked the bugs out” • I fixed the problem, that bugs no longer exist in my program
  • 31. Control of debugging • F5 – step into • F6 – step over • F7 – step return • Ctrl+F2 (red square) - terminate
  • 32.
  • 33. When you return from emptyVase(7) continue from this place: Line 13
  • 34. Debugging of Carrot problem • int main () { • setvbuf(stdout, NULL, _IONBF, 0); • int rabbits[5]; • int carrots=1; • int i; • for (i=0; i<6; i++){ • rabbits[i]=carrots; • carrots+=3; • if (carrots>=16) • carrots=1; • } • for (i=0; i<6; i++) • Printf(“%i, ”, rabbits[i]); • return 0; • }
  • 36. Compiler errors 4 Errors in Line 29 1 Warning in line 27. Error in Line 29 fixing: replace comas with semicolons