/* This is HW4_2 Lab EE107
The purpose of this function to calculate the square roots
Creating the code and free of syntax and grammatical errors.
Author: Ekwegbalum Unachukwu
Star ID:do2170dt
Due Date: April 26th, 2024.
*/
#include <stdio.h>


// Function to compute the absolute value of a number
float absoluteValue(float x) {
    if (x < 0)
        x = -x; // If x is negative, make it positive
    return x; // Return the absolute value
}

// Function to compute the square root of a number
float squareRoot(float x) {
    const float epsilon = 0.00001; // Threshold for convergence
    float guess = 1.0; // Initial guess for square root

    // Handling negative input
    if (x < 0) {
        printf("Cannot compute square root of a negative number.\n"); // Display error message
        return -1.0; // Return a flag value indicating error
    }

    // Iterative approach to compute square root
    while (absoluteValue(guess * guess - x) >= epsilon) {
        guess = (x / guess + guess) / 2.0; // Update the guess
    }

    return guess; // Return the computed square root
}

// Main function
int main(void) {
    // Test cases
    printf("square root of (2.0) = %f\n", squareRoot(2.0));
    printf("square root of (144.0) = %f\n", squareRoot(144.0));
    printf("square root of (17.5) = %f\n", squareRoot(17.5));
    printf("square root of (-9.0) = %f\n", squareRoot(-9.0)); // Testing with a negative number
    return 0; // Indicate successful completion
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: