Monday, 18 March 2019

Write a C Program to Find the Square Root of a Number

C Program To Find The Square Root Of a Given Number Without sqrt Function


In this C program, we have to find the square root of the number given by the user without using any function.

C Program To Find The Square Root Of a Given Number


In C we have sqrt pre-defined function thta will the square root of the number in the math.h header file. But in this C program, we will not use this sqrt function but we will use a different approach to find the square root of the number.

 Algorithm for the C Program


1. Read a number, say s.
2. If s<0, then go to step 16
3. Else if s=0
4. Print the value of sq as 0
5. Else
6. Set n=1
7. While(!(s>=n*n&&s<(n+1)*(n+1))
8. Do increment n by 1
9. End While
10. d=s-(n*n)
11. P=(double)d/(2*a)
12. a=(double)n+p
13. root=(double)a-((p*p)/(2*a));
14. Print the value of root.
15. Endif
16. Exit


Source Code For the C Program to Find Square root of the number


#include<stdio.h>
#include<conio.h>
void main()
{
    int s,n;
    double d,p,a,root;
    clrscr();
    printf("Enter a Number : ");
    scanf("%d",&s);
    if(s<0)
              printf("Enter a positive number ");
    else if(s==0)
              printf("square root of 0 is 0");
    else
    {
              n=1;
              while(!(s>=n*n && s<(n-1)*(n+1)))
              {
                    n++;
               }
                 d=s-(n*n);
                 p=(double)d/(2*n);
                 a=(double)n+p;
                 root=(double)a-((p*p)/(2*a));
                 printf("\n Square root of %d is %.3f",s,root);
       } 
   getch();
}



Output of the C program :

Enter a number : 16
Square root of the 16 is 4.000         
 

2 comments:

  1. could you recommend some good text editor for code and compiler ? are you using Sublime ?

    ReplyDelete
  2. I usually use CodeBlocks but there are many editors with their different features. You can use notepad++, Eclipse for C. Sublime is also very good.

    ReplyDelete