To start of this tutorial, lam going to explain what the square root of a number means.
The square root of a number B is a number A such that A2 = B. In other words, a number A when multiplied by itself (squared i.e. A2), B is the outcome. For example, 4 is the square root of 16, which means 4 was multiplied by itself (squared i.e. 42) to get 16.
Okay let’s get into the coding part of how one can achieve calculating the square root of a number in simplest and accurate way possible.
The code in SquareRoot.c above is the code that you can use to obtain the square root of a number.
On line 1 and line 2, I included the header files, i.e. stdio.h and math.h respectively.
On line 4 is where the main method begins from and the code block which starts from line 5 to line 13 executes under it.
On line 6 and sqrt() I basically do declaring of variables num and squareRoot respective and also assign values to them. I have declared both num and squareRoot as double for two reasons
- The sqrt() function that is used on line 8 takes in an argument of data type double and the value stored in num is the one that is provided to that function hence having to be a double
- The sqrt() function return a a numeric value of data type double, hence the variable squareRoot which is to be assigned the returned value from the sqrt() function being declared as a double.
So the sqrt() function computes the square root of a number that is provided to it as an argument. Recall that on line 2 I included math.h header file, I did so because the sqrt() function cannot be used if that header file is not included.
Variable num stores the number whose square root is to be calculated and squareRoot stores the square root of the number stored in variable num.
On line 10 that’s where printing of the formatted string containing the answer is done.
On line 12 that’s where a value is returned to main calling function.
On line 13 that’s where the main code block is closed off.
I have explained it all. So compile that code and run it. On running the code you will get an out come as the ones shown in the screenshot below. I used the red border to highlight the output of the code in SquareRoot.c.
Hope you have enjoyed the tutorial. You can down the source code below.