1

Basically i want to create a recursive function to implement this program in C

#include <stdio.h>
main()
{
    float guess=1,num,num1;
    int i;
    printf("enter any number:\n");
    scanf("%f",&num);
    num1=num;
    for (i=1;num1>1;i++,num1/=10); //to calculate no of digits in input
    i=i/2;
    printf("i:%d\n",i);             //to make a better guess
    for (;i>0;i--,guess*=10);
    printf("guess = %f\n",guess);

    for (i=1;i<=10;i++)      //evaluate square root improving accuracy with each loop
    {
        guess=(guess+num/guess)/2;
    }
    printf("sqrt: %f\n",guess);  
}
7
  • 3
    Aaaand...what happens when you run it? Commented Aug 9, 2011 at 19:53
  • 1
    Why does it have to be recursive? Commented Aug 9, 2011 at 19:53
  • 1
    And you need help with... what? Commented Aug 9, 2011 at 19:54
  • 2
    Homework much? Show us how you have tried to implement the recursive function and we'll help you fix any mistakes. Commented Aug 9, 2011 at 19:54
  • 7
    Any loop can be turned into a recursive function. Random people on the Internet will not always be willing to do this for you. Figure out how to do it for yourself. Commented Aug 9, 2011 at 19:58

1 Answer 1

9

Something like this:

#include <math.h>
#include <float.h>

float MySqrt(float num, float prev)
{
    float next = (prev+num/prev)/2;
    if (fabs(next-prev)<FLT_EPSILON*next)
        return next;
    return MySqrt(num, next);
}

To call it, pass 1.0 as your initial guess for the prev parameter.

You can easily make this fail with a stack overflow by passing in bad data, but you probably aren't going to be tested on that in this assignment.

Sign up to request clarification or add additional context in comments.

11 Comments

fixed point fixed point srry for the pun.. :)
Suggested improvement: use FLT_EPSILON from <float.h> in place of hardcoded 1e-6.
@yi_H OK, now I get it. I do actually have a PhD in Pure Maths but that was so long ago, and I'm so immersed in computed than the only thing I could make fixed point into was the counter part to floating point! Shame on me!
@Alexandre Good point. I suspect that you could even get away with testing next==prev.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.