C# – Calculating square root with two classes

This program will calculate square root with two classes. It is really a fascinating program, due to the fact that it uses precalculation in the class SqrtPrecalculated.

Thus, if you need plenty of calculations, once the values are precalculated it will simply give you the values and not calculate them once again. Thus, it is really fast. Actually, you will not notice it unless you are using a really slow PC or you write a separate code to test the calculation time of a root. But anyway, this is the content of the class sqrtPrecalculated.cs

What this class does?

1. We have initialization of a constant MaxValue and Array sqrtValues.

2. In the method SqrtPrecalculated we recalculate all the square roots from 0 to 100000 (we reach this number in the array by using the +1, due to the fact that the arrays start from 0.

3. In the method GetSqrt, we check about the size of the given number – if it is not between 0 and 100000 we return exception.

4. If it is OK, we return the precalculated value.

The main method is in another class.

It looks like this:

It simply asks for input of a number and sets it as attribute of the method “SqrtPrecalculated”. Then it returns the value.

If you give 0 as input, the program exits the while/do loop and thanks you for visiting my site!

If you want to see the program in action, you may download it from here.

Some of the code of the current article is part of the free Bulgarian C# programming book.

About

VBA Developer