# Java Practice Assignment #5 – Recursive Factorial

by on February 21, 2013

As always, I’ll include my solution to the previous assignment before I give you the requirements for the next assignment. Here’s my video walk-through of assignment 4:

## Recursive Factorial Assignment

Since you have now learned about recursion in Java, now it’s time to put that knowledge to the test! Your job will be to implement a recursive method that will be able to calculate any given number’s factorial.

First off, if you don’t know what a factorial is, allow me to explain. A factorial is a calculation based on multiplying a given number by it’s decrementing values until you reach the number 1. The notation for this is a given number following by an exclamation mark. Let’s look at some examples, as they will make this explanation make sense:

2! = 2 x 1 = 2 3! = 3 x 2 x 1 = 6 4! = 4 x 3 x 2 x 1 = 24 5! = 5 x 4 x 3 x 2 x 1 = 120 6! = 6 x 5 x 4 x 3 x 2 x 1 = 720

Does that make sense to you? All we do is take the original number and then multiply it by the number lower than it by 1… rinse and repeat until we get to 1.

So if you remember the important aspects of a recursive algorithm, you’ll remember that you must have an ending point, and a constant progression towards that ending point.

## Explanation of How to Setup this Assignment

Here’s a quick video that will walk you through how to setup this assignment on your computer:

Top 7 Tools Java Professionals Use Daily
 The best part is, 85% of these tools are FREE Download this 1-page PDF that will show you exactly how to get your hands on all these tools today.

Bernd February 22, 2013 at 12:01 pm

Very simple assignment, no problem…

But this arises a big Java problem, at least in my opinion: Why is there no such thing as “Numeric Overflow Error / Exception”??? I would expect this from any programming language!

Dealing with “int” as your assignment is coded, starting from factorial(13) you get wrong results without notice, being sometimes nagative and constantly 0 from (34) onwards.

Robb G April 11, 2013 at 11:04 pm

Trevor, I just watched your video which shows your solution to this assignment(5) which included the use of an instance variable “total.” I had come up with the following which doesn’t require an instance variable and follows a little different logic than what you did. It passed your junit tests including the 5th one to make sure it’s recursive.

public int factorial(int value) { if (value==1) return 1; return (value*factorial(value-1)); }

Trevor Page April 12, 2013 at 10:07 am

Nice work Robb

wessley sang May 31, 2013 at 8:19 am

please assist on this.:using queues to rervese string of characters in java

Previous post:

Next post: