#include <stdio.h>
#include <stdlib.h>

double cubic (double, double, double, double, double);
/* Calculate the value of a cubic at x given its form */
double dcubic (double, double, double, double);
/* Do the same for the first derivative of a cubic */

const int MAXLEN = 100;  /* Maximum length of strings input */
const int MAXSTEPS = 100; /* No. of steps we will use to get approximation */


int main(int argc, char *argv[])
// Program does Newton-Raphson approximation on a cubic
// ax^3 + bx^2 + cx + d

{
    double a= 1.0;  //a, b, c and d are parameters of cubic
    double b= -8.0;
    double c= 19.0;
    double d= -12.0;
    int i;
    double guess;  /* Initial guessed root */
    double root;   /* Actual answer root */
    char input_line[MAXLEN]; /* Line of input from user */
	double diff;		// Output of differentiated cubic
    
    printf ("Input an initial guess for a root >");
    fgets (input_line, MAXLEN, stdin);
    guess= atof(input_line);
    root= guess;
    for (i= 0; i < MAXSTEPS; i++) {
		diff= dcubic(root, a, b , c);
        if (diff == 0) {
			printf("Root has f'(x)=0 for x= %f\n",root);
			return -1;
		}
		root= root- cubic(root,a,b,c,d)/
            diff;
    }
    printf ("After %d steps, initial %f gave a root of %f\n",i,guess, root);
    return 0;
}

double cubic (double x, double a, double b, double c, double d)
/* Returns the value of a cubic at ax^3+bx^2+cx+d*/
{
    double answer;
    answer= x*x*x*a;
    answer+= x*x*b;
    answer+= x*c;
    answer+= d;
    return answer;
}



double dcubic (double x, double a, double b, double c)

/* Returns the first differential of a cubic ax^3+bx^2+cx+d
Note that d is not needed as input */
{
   double answer;
   answer= 3*x*x*a;
   answer+= 2*x*b;
   answer+= c;
   return answer;


}

