Saturday 20 August 2011

C++ program to find square root of a perfect square number- without library function

It is a simple program, but using this logic is interesting , So i post it here.
Logic:
Consider the number 25

ie n=25

Count =0;

Subtract 1 from 25(count =1)
Subtract 3 from 24(count =2)
Subtract 5 from 21(count =3)
Subtract 7 from16(count =4)
Subtract 9 from 9  (count=5)
(ie subtract  until 0 )
Now the value of count gives the square root of  the number

#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
     int p,i,count=0,n;
     cout<<"Enter the number\n";
     cin>>n;
     p=n;
     for(i=1;p!=0;i=i+2)
     {
           p=p-i;
          
          
           count=count+1;
     }
          
     cout<<"Square root of"<<n<<"="<<count;
         
     getch();
         
  }

1 comments:

C++ program to find Square Root of a Number

Thanks for sharing this code. It's really helpful. Keep sharing.

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More