Tag Archives: recursion

Pascal’s Triangle Recursion example

Pascal’s Triangle

Pascals Triangle presents a simple formula for expanding binomials. If you think a little bit about how Pascal’s Triangle determines each term, you should see that a recursive method is used!

The animation below demonstrates the recursive nature of Pascal’s Triangle.

Part I

Objective: to employ recursion to be able to print out an entire line of Pascal’s Triangle . Look at the animation, getting a particular term in a line is inherently recursive. This class should throw an ArithmeticException if you attempt to calculate an invalid Term. (quick example of how to throw an Exception)

Hint: You only need to use recusion to get the term of the expansion.

Part II

Now that you can print out an entire line of Pascal’s Triangle. Print out the entire triangle up to some degree ‘n’.

java-recursion-excercises-1

void countDown(int num)

Description: This method prints the numbers from num down to and including on new lines

Method Call output
countDown(5) 5
4
3
2
1
0
countDown(3) 3
2
1
0
void printRev(String s)

Description: This method prints each letter of String s on new lines in reverse order.

Method Call output
printRev(“abcdef”) a
b
c
d
e
f
printRev(“abc”) a
b
c

 

int sumLessthan(int n)

Description: This method returns the sum of all positive integers less than or equal to n

Method Call output
sumLessThan(4)   10 (4+3+2+1)
sumLessThan( 5 )  15 ( 5 + 4 + 3 + 2 + 1)

 

int sumLessthan(int n)

Description: This method returns the sum of all positive integers less than or equal to n

Method Call output
sumLessThan(4)   10 (4+3+2+1)
sumLessThan( 5 )  15 ( 5 + 4 + 3 + 2 + 1)

 

double average( int[] nums, int index)

Description: This method returns the average of all the elements in nums. The parameter ‘idnex’ is used to keep track of how far along you have gone in the array.

Method Call output
average({3,2,1}, 0)   2
average({3,2,2}, 0)    2.333333

Recursion in Java

Recur

bunnyEars2() (try to figure out what goes where the question marks are)

Recursion problems (bunny ears is a good, straight forward one to start with)