Sunday, March 25, 2012

PROGRAM TO FIND SQUARE ROOT OF A NUMBER - C CODE

#include<stdio.h>

float SquareRoot(float num);

int main()
{
    float input, ans;

    printf("\n Enter The Number : ");
    while(scanf("%f", &input) == 1)
    {
        ans = SquareRoot(input);
        printf("\n Square Root : %f\n", ans);
    }
    return 0;
}
float SquareRoot(float num)
{
    if(num >= 0)
    {
        float x = num;
        int i;
        for(i = 0; i < 20; i ++)
        {
            x = (((x * x) + num) / (2 * x));
        }
        return x;
    }
}

3 comments:

  1. plz can u explain me logic ?i didnt understand

    ReplyDelete
  2. pls change the while loop to if as the looping part is infinite program is

    #include
    #include
    float SquareRoot(float num);

    int main()
    {
    float input, ans;
    clrscr();
    printf("\n Enter The Number : ");
    scanf("%f", &input);
    if( input >= 0)
    {
    ans = SquareRoot(input);
    printf("\n Square Root : %f\n", ans);
    }
    return 0;
    getch();
    }
    float SquareRoot(float num)
    {
    if(num >= 0)
    {
    float x = num;
    int i;
    for(i = 0; i < 20; i ++)
    {
    x = (((x * x) + num) / (2 * x));
    }
    return x;
    }
    }

    ReplyDelete