// Arup Guha
// 10/12/2011
// Written in COP 3223H - Functions!

#include <stdio.h>
#include <math.h>

void printcharrepeat(int numtimes, char c);
int fact(int n);
double my_fabs(double n);
double my_sqrt(double n);

int main() {

    // Repeat some characters several times.
    int i;
    for (i=0; i<10; i++) {
        printcharrepeat(i, 'a'+i);
        printf("\n");
    }

    // Test our factorial function.
    printf("8! = %d\n", fact(8));

    // and our square root function...
    double number;
    printf("Enter a number to find a square root of\n");
    scanf("%lf", &number);
    printf("The square root of %lf is %lf.\n", number, my_sqrt(number));
    printf("The real square is %lf\n", sqrt(number));

    return 0;
}

// Precondition: numtimes is positive and c is printable.
// Postcondition: c will be printed numtimes times.
void printcharrepeat(int numtimes, char c) {

    int i;
    for (i=1; i<=numtimes; i++)
        printf("%c", c);


}

// Preconditions: 0 <= n <= 12
// Postcondtions: returns n!
int fact(int n) {

    // Multiply in each number from 1 to n.
    int i, ans = 1;
    for (i=1; i<=n; i++)
        ans = ans*i;

    return ans;
}

// Preconditions: None
// Postconditions: returns the absolute value of n.
double my_fabs(double n) {

    if (n < 0)
        return -n;
    return n;
}

// Precondition: n > 0.
// Postcondition: The approximate value of the square root of n is returned.
double my_sqrt(double n) {

    // My initial guesses.
    double low = 1, high = n;

    // Flips for numbers less than 1.
    if (n < 1) {
        low = n;
        high = 1;
    }

    double guess = (low+high)/2;

    // Keep on guessing until you get a good one.
    while ( my_fabs(guess*guess - n) > 1e-7 ) {

        // Adjust high or low as necessary.
        if (guess*guess > n)
            high = guess;
        else
            low = guess;

        guess = (low + high)/2;

    }

    return guess;
}
