Square root

Square root

Newton’s method of calculating a square root.

5² = 25, so √25 = 5, or expressed another way, 5 * 5 = 25, so the square root of 25 is 5. Newton’s method is one way to calculate the square root of a number.

Make


Write a program that outputs the square root of a number using Newton’s method.

Use this boilerplate code as a starting point:

Success Criteria

Remember to add a comment before a subprogram, selection or iteration statement to explain its purpose.

Complete the subprogram called `sqroot` that:

  1. Takes the parameter x which is the number to square root.
  2. root = x at the start of the algorithm.
  3. root is repeatedly recalculated as 0.5 * (root + (x / root)) until the value of root does not change.

For example, the square root of 64 can be calculated in the sequence of steps:

64

32.5

17.234615384615385

10.474036101145005

8.292191785986859

8.005147977880979

8.000001655289593

8.00000000000017

8.0

8.0 – This value equals the previous value of root, so the algorithm is complete.

Complete the `main program` so that:

  1. The user can input a positive decimal number to square root.
  2. The square root is output.

Typical inputs and outputs from the program would be:

Enter a number: 25

The square root of 25.0 is 5.0


Enter a number: 64

The square root of 64.0 is 8.0

Knowledge Organiser

Use these resources as a reference to help you meet the success criteria.

Programming guide:

Evaluate


Run the unit tests below to check that your program has met the success criteria.

Enter a number: 18.49

The square root of 18.49 is 4.3

Enter a number: 36

The square root of 36.0 is 6.0

Enter a number: 49

The square root of 49.0 is 7.0

Enter a number: 200

The square root of 200.0 is 14.142135623730951

Check that you have:

  • Used comments within the code to describe the purpose of subprograms, conditions and iterations.
  • Used meaningful identifier names. That means the names of subprograms and variables indicate what they are for.
Craig'n'Dave logo

Craig ‘n’ Dave

In partnership with

Mission Encodeable
Bett Awards 2024 Finalist