I need help using recursion in OOP: : A level 1 tree is a line. A level 2 tree is a line and two level 1 trees (it looks like: Y). A level 3 tree is a line and two level 2 trees. A level 4 tree is a line and two level 3 trees.
1 view (last 30 days)
Show older comments
I have a class set up with functions to drive forward and make turns. I just don't know how to make this work in a loop. The following is what the program should do for a n-level tree. If n is 0, do nothing. Otherwise, drive forward d, turn left a degrees, draw a level n-1 tree, turn right 2a degrees, draw a level n-1 tree, turn left a degrees, and drive backward d
Answers (1)
Steven Lord
on 14 Oct 2016
Ah, LOGO and turtle graphics. That takes me back ... longer ago than I'd care to admit.
Is the code you posted in a function named tree or something similar? If it is, what input arguments does the function accept? If it is not in a function, you should create a function named tree. For this to be a recursive program, the tree function will have to call itself.
I would put each clause (a section ending in a period or a comma) in your instructions on how to draw the tree on a separate line of your file as a comment. Then after each of those comment lines, write a single command that does what the comment line says to do.
4 Comments
Steven Lord
on 17 Oct 2016
Almost. You've defined tree to have two inputs, obj and n. You're calling it in your recursive step with one input, just n-1. You should call it with two inputs, obj and n-1. Otherwise at the recursion step when you execute "if n <=0" the variable n won't exist and you'll receive an error.
See Also
Categories
Find more on Software Development Tools in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!