The square root of a number can be found recursively without too much trouble. The idea is to make an initial guess (called previousGuess in the pseudocode). You then make a next guess (called nextGuess) based on the previous guess and the original number. You repeat this process until the difference between guesses is a very small positive number.
Write a Java program which finds the square root of a positive number recursively using the following outline/pseudo code:
Create an array of numbers. The numbers in the array will be: 9, 17, 25, 37, 49, 55, 999
Using a for loop find the square root of each number in the array using this procedure
Calculate a guess of the root by generating a random number between 1 and the first number in the array. Call this number previousGuess
Print the number and the first Guess
Call a method called FindtheRoot...this is the recursive method
send the method previousGuess and the number whose root you are finding
this method will calculate and return the square root of the given number.
DO NOT use a built in math function
You must use recursion for full credit (although there are other ways to process this)
Print:
the number
the returned root formatted to display 4 places to the right of the decimal (ten thousandths)
label the output with appropriate text
Process the next number in the array
FindTheRoot
We need 2 "guesses" at the square root so we can compare them.
Calculate the next guess using the formula
next guess will be equal to: (your previous guess + target number/your previous guess)/2
If the difference of the two guesses(previous and next) is less than 0.00001 apart (but must be positive)
return the next guess as the square root
If the difference is not less than 0.00001 apart then
Print:
the next guess formatted to display 4 places to the right of the decimal (ten thousandths) - label the output with appropriate text
call FindTheRoot sending it the nextguess and the target number...this is the recursive call
return the value sent back from the call to the method
Sample output. Our roots will all be the same but our numbers to get there will differ
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference
and should not be submitted as is. We are not held liable for any misuse of the solutions.
Please see the frequently asked questions page
for further questions and inquiries.
Kindly complete the form.
Please provide a valid email address and we will get back to you within 24 hours.
Payment is through PayPal, Buy me a Coffee
or Cryptocurrency.
We are a nonprofit organization however we need funds to keep this organization operating
and to be able to complete our research and development projects.