I wrote this code for a homework problem. The question asks for the inputs to be an array representing a polynomial along with the degree of the polynomial and the value of x. Then it has to return the derivative of the polynomial. Until I ask the program to output the derivative it works (maybe not the cleanest, nicest program, but it does what it has to). I'm trying to create an array function to return the derivative but I don't know how to code it properly. What I am trying to say in the function is that the derivative should be i*polynomial^(i-1), but so far I haven't had any success with that. Here is what I have so far.

#include<iostream>
#include<cmath>

using namespace std;

int drv(int[]);

int main()
{
	int total;
	cout << "Enter the degrees of polynomials: ";
	cin >> total;
	
	int polynomial[total];
	
	for (int i=total; i>=0; i--)
	{
		cout << "Enter the coefficient for the variable of degree " << i << ": ";
		cin >> polynomial[i];
		cout << "The term representing the variable of degree " << i << " is " << polynomial[i] << "x^" << i << endl;
	}
	
	cout << "The derivative of the entered polynomial is: " << drv(polynomial);
	
    return 0;
}

int drv(int[])
{

The derivative will not be a single integer, I think you want the value of the derivative at a specific point, in that case you will need to be given the point (x). Also, how are you supposed to know how long the array is if you don't pass a dimension? I would suggest something like this:

int * differentiate(int [] coefficients, int numCoefficients)
{
    int *ret=new int[numCoefficients];
    for (int i=0; i<numCoefficients; ++i)
        //recalculate coefficients and put them in ret here
    return ret;
}
int differential(int coefficients[], int numCoefficients, int x)
{
    int ret=0;
    for (int i=0; i<numCoefficients; ++i)
        ret+=x*i*pow(coefficients[i],i-1);
    return ret;
}

Edited 4 Years Ago by Labdabeta: code tags got messed up

Use pencil and paper. Start with

3x^2 - 4x + 1

Rewrite this as:
3x^2 + (-4)x^1 + 1x^0

If I remember correctly the first derivative is

6x - 4

and the second derivative is

6

The general protocol to determine the value of any given term in the next derivative is as follows:

A) the coefficient of the new term is the coefficient of the current term
times the exponent of current term
B) the exponent of the new term is the exponent of the current term minus one
C) don't show terms with coefficients of zero

Edited 4 Years Ago by Lerner: n/a

This article has been dead for over six months. Start a new discussion instead.