In: Computer Science
Writing a squareroot program in C++ using only:
#include <iostream>
using namespace std;
The program must be very basic. Please don't use math sqrt. Assume that the user does not input anything less than 0. For example: the integer square root of 16 is 4 because 4 squared is 16. The integer square root of 18 is 5 because 4 squared is 16 and 5 squared is 25, so 18 is bigger than 16 but less than 25.
Please find your solution below and if any doubt comment and do upvote.
Code:
#include <iostream>
using namespace std;
//function to find square root
int squareroot(int n)
{
//if nuumber is 0 or 1 return
if(n==0||n==1)
{
return n;
}
int root,i;
//traverse the loop till i*i<=n
for(i=1;i*i<=n;i++)
{
root=i;
}
--i;
//eg. n=16
//i*i<=n
//1*1<=16
//2*2<=16
//3*3<=16
//4*4<=16
//5*5<=16 false and break;
//the subtractet 1 from i and check if that equals n then return that number as root else increment 1 in root the return
//if number has pefect root
if(i*i==n)
return root;
else
return root+1;//if number not have perfect root
}
int main()
{
cout<<"squareroot "<<squareroot(16)<<endl;
cout<<"squareroot "<<squareroot(18)<<endl;
cout<<"squareroot "<<squareroot(11)<<endl;
cout<<"squareroot "<<squareroot(48)<<endl;
return 0;
}
OUTPUT: