RecursionWithDrawingPanel
Download
Report
Transcript RecursionWithDrawingPanel
Recursion
Pepper
Another way to loop
Call yourself repeatedly until you say to stop.
Example:
add up 10 numbers using addUp.
-- Input – number to count
-- Ouput – total of all those numbers added up
Logic:
If the number I am counting is 0, just return 0.
If the number I am counting is anything else, return the number I have +
the total of all the rest (the number I have – 1)
Requires:
• Trust the function will do its job
• A stopper
• A way to reach the stopper (decrement or increment)
Code the addUp method and call it to addUp(10)
addUp Solution
public class AddUp
{
public static void main()
{
System.out.println(addUp(10));
}
public static int addUp(int numberToCount)
{
if (numberToCount == 0)
{
return numberToCount;}
else
{
return numberToCount + addUp(numberToCount-1);
}
}
Create a string of stars
starString routine
-- Input – number of stars needed
-- Ouput – String of that many stars
Logic:
If the number I am counting is 1, just return 1 star.
If the number I am counting is anything else, return one star + all the rest of the
stars (the number I have – 1)
Requires:
• Trust the function will do its job
• A stopper
• A way to reach the stopper (decrement or increment)
Code the starString method and call it to create starString(10)
String of Stars
public static String starString (int numberStars)
{
if (numberStars == 0)
{
return("");
}
else
{
return "*" + starString(numberStars-1);
}
}
Work with shapes
• Divide a rectangle up 4 levels deep
– First print 1 big square
– Then divide that one square
– Test fully
– Then create another method to
printInsideSquares with input: level,
paintbrush, starting x,y and size.
• Stop at level 1 – just print the square with no
division
• At every other level, print a big square and
printInsideSquares for the smaller squares
Work with Shapes
First hint: Here is how to draw 1 level of 4 squares inside 1 square:
public static void printOneInsideSquares(int level,
Graphics g, int x, int y, int size)
{
g.drawRect(x,y,size,size);
g.drawRect( x,y,size/2,size/2); // top left
g.drawRect( x+(size/2), y,size/2,size/2); // top right
g.drawRect( x,y+size/2,size/2,size/2); // bottom left
g.drawRect( x+size/2,y+size/2,size/2,size/2); // bottom right
}
Now – add the level logic:
stopper:
If level == 1, just draw the main rectangle
do a job and call itself to do the rest:
If level higher, draw main
rectangle and printInsideSquares of the small squares at the next
level.