I'm just starting with recursive functions and know a some of how c++ works but I really don't understand how this code:
void q9_draw_triangle(int a, int b) {
// a is the starting point, b is the end
if (a > b) return;
// print pattern first
for(int i = 0; i < a; i++){
std::cout << "-";
}
std::cout << std::endl;
// call on triangle where a is incremented once
q9_draw_triangle(a+1,b);
// print pattern last
for(int i = 0; i < a; i++){
std::cout << "-";
}
std::cout << std::endl;
}
I get how the upper half works, it draws the first half of the triangle. When I stepped through this code using a debugger, once a > b happened it jumped to the last closing brace then to the last for loop and started drawing the second half of the triangle and decrementing itself back down to the starting a value. I have no idea why this happened or how one would know to do this to decrement.
Any help in understanding this is appreciated!
Aucun commentaire:
Enregistrer un commentaire