Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  squareroot
Language: C/C++
Code:
          



#include<stdio.h>
#include<string.h>
#include<stdlib.h> 
#include<math.h>

#define MAXDIGIT 10



int main(int argc, char *argv[] )
{
  int i=0,length=0,inputnum=0;
  char input[MAXDIGIT]= "";
  float x=1;
  float y=2;
  char useropt='y';

   
   do
   {

       printf("Hello!Please enter the positive integer for finding it's square root. Maximum allowed length of number is 10: \n");
   
   scanf("%s",input);
   length=strlen(input);
    
   if(length>10)
   {
      printf("Sorry! Length exceeds the maximum allowable size. Try again!\n");
     break;
   }

   for(i=0;i<length;i++)
   {
      if(!isdigit(input[i]))
      {
            printf("Sorry! Input is not a number. Try again! \n");
     break;
      }
   }
 

   inputnum=atoi(input);

   if(inputnum<0)
   {
     printf("The number you entered is a negative number. Try again! \n");
     break;
   }

   //printf("The number you entered is %d",inputnum);
  
   
          if(inputnum=0 || inputnum=1)
          {
               printf("The square root of %d is %d",inputnum,inputnum);
               break;
          }
          else if(inputnum=2)
               {
                 printf("The square root of 2 is 1.414\n");
                 break;
               }

 
 
       while(x<=inputnum/2)
       {
              if(inputnum > x*x && inputnum > y*y)
              {
                       x=x+1;
                    y=y+1;
              }
              else if(inputnum > x*x && inputnum < y*y)
              {
                         int temp=(x+y)/2;
                          
                          if( temp*temp < inputnum)
                          {  
                         x=temp;
                           }          
                          else y=temp;

                                      if(fabsf(x*x - inputnum)< 0.01)
                          {
                         printf("The square root of the entered number is %f\n",x);
                         break;
                          }
                          else if(fabs(y*y - inputnum)< 0.01)
                             {
                              printf("The square root of the entered number is %f\n",y);
                                                break;
                             }
               }

       }

      
      printf("Do you want to continue? hit 'n' to exit and any other character to continue!\n");
      
      scanf("%c",&useropt);
          


   }//end of do 
   while(useropt != 'n');
Comments: