There are many algorithms to find square root of the number !
Here is the probably coolest and very easy method to find square root in C .
What this method actually is , guessing a number , squaring it , if the difference between square of a guess number and original number is acceptable than assigning the guess number as square root and if not updating the guess number .
Algorithm :
Here is the probably coolest and very easy method to find square root in C .
What this method actually is , guessing a number , squaring it , if the difference between square of a guess number and original number is acceptable than assigning the guess number as square root and if not updating the guess number .
Algorithm :
- Given a number say x.
- Guess the square root of the number , say guess=x/2.
- Square your guessed number and subtract it from original number.
- If the absolute difference is less than the acceptable tolerance , say ACCURACY , then you are done .
- Else calculate new guess number .
guess = (guess + (original /guess))/2 . - Go to step 3.
C Program : Finding Square Root
#include < stdio.h >
#define ACCURACY 0.001 // tolerance : you can set by yourself according to requirement
int main()
{
float number,guess,square_root;
printf("Enter a number to find square root of it:\n");
scanf("%f",&number);// storing the number
guess=number/2;// initializing guess number
while((guess*guess - number) > ACCURACY)//loop runs until the square root is found
{
guess = (guess + number/guess )/2;// updating the guess number
}
square_root = guess;//assigning the value of guess number to square root.
printf("square root of %.2f = %.4f",number,square_root);//final answer
}
Thanking you !
Thanks a lot Sir, this program is much easier to understand according to the concept. Other programs on the internet takes x and y which is hard to understand.
ReplyDelete