Sunday 15 June 2014

C++ program to find square root of a number

C++ program to find square root of a number using sqrt() function, without using sqrt() , using recursion, function.

Algorithm to calculate square root of a number( let's calculate square root of 1000 )
  1. Find the number whose square is near to the given number(32 square(1024) is near to 1000)
  2. Now divide the given number by that number and add the result to that number (32+1000/32)
  3. Now divide the new number by 2, this is our new number.
  4. Repeat step 2 to 3 four or more times to get more accurate result.



C++ program to find square root of a number using sqrt() function


#include <iostream>
#include<math.h>
using namespace std;
int main()
{
    float num,result;
    cout<<"Enter the number ";
    cin>>num;
    result=sqrt(num);
    cout<<"Square root of the "<<num<<" is "<<result;
    return 0;
}




C++ program to find square root of a number without using sqrt() function


#include<iostream>
using namespace std;
int main()
{
    float num,i;
    cout<<"Enter the value ";
    cin>>num;
    for(i=1;i*i<num;i++);
    if(i*i==num)
      cout<<"Square root of "<<num<<" is "<<i;
    else
    {
       for(int j=0;j<4;j++)
       {
           i+=num/i;
           i=i/2;
       }
    }
    cout<<"Square root of "<<num<<" is "<<i;
    return 0;
}



C++ program to find square root of a number using function


#include<iostream>
using namespace std;
float root(float num)
{
    float i;
    for(i=1;i*i<num;i++);
    if(i*i==num)
      return i;
    else
    {
        for(int j=0;j<4;j++)
        {
            i+=num/i;
            i=i/2;
        }
    }
    return i;
}
int main()
{
       float num;
       float srt;
       cout<<"Enter the value ";
       cin>>num;
       srt=root(num);
       cout<<"Square root of "<<num<<" is "<<srt;
       return 0;
}


C++ program to find square root of a number using recursion


#include<iostream>
using namespace std;
void root(float num,float &i,int j)
{
    if(j==4)
        return;
    i+=num/i;
    i=i/2;
    root(num,i,j+1);
}
int main()
{
    float num,i;
    cout<<"Enter the value ";
    cin>>num;
    for(i=1;i*i<num;i++);
    root(num,i,0);
    cout<<"Square root of "<<num<<" is "<<i;
    return 0;
}




No comments:

Post a Comment