DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

# Thread: challenge from The First Book of Java

1. Registered User
Join Date
Oct 2006
Posts
2

## challenge from The First Book of Java

1)Prompt the user and accept a number from standard input.
2)Prompt the user and accept a symbol character from standard input. The symbol must be either an ^ or an !. If it is neither of these, display an error message and end the program.
3)If the symbol is a !, compute the factorial of the number entered in step 1 and display the result.
4) if the symbol is a ^, prompt the user to enter a second number, and then calculate the 1st number to the power of the 2nd number (similar to tonight's exercise). Display the result.
5) You must use iteration/loops for the factorial and exponent calculations

can't use math class

2. Registered User
Join Date
Jul 2005
Posts
78
easy.

3. Registered User
Join Date
Oct 2006
Posts
2
no idea how to do this without the math class

4. Senior Member
Join Date
Dec 2004
Location
San Bernardino County, California
Posts
1,468
Given n, factorial is the result of multiplying the numbers 1 to n ... so you can create a for loop which counts up to n, multiplying "current result" by the current value of your counter

Given x to the power of y, you multiply x by itself y times. Make sure to test for the special cases of y being 0, y being 1; if not a special case then counting from 2 to y, with the new result in each iteration being current result times x.

You CAN write each of these as a recursive algorithm.
Last edited by nspils; 10-05-2006 at 08:41 PM.

5. Registered User
Join Date
Jul 2005
Posts
78
I did them as a loop; not much experience with recursion, but i have done similar things before.

.

4! = 1 * 2 * 3 * 4
You can loop that.

You can also use recursion:
4! = 3! * 4

For powers:
2^4 = 2 * 2 * 2 * 2
x^0 = 1
Last edited by masher; 10-05-2006 at 09:37 PM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts

 FAQ Latest Articles Java .NET XML Database Enterprise