Calculate Derivative Functions in C++

So, guys today we will learn How to calculate the Derivative of a Function in C++. Let’s do it together. The topic is basically to find the derivative of an equation.

The derivative of a function is the rate at which the function value is changing, with respect to x, at a given value of x. Graphically we can say that derivative is nothing but a slope at a particular point of a function.

How to calculate Derivative Functions in C++

Most of you might be knowing how to find a derivative of a function but some may find it confusing so let us have look at how it is calculated. Steps for finding the derivative of function are as follows:

  1. Identify the variable terms and constant terms in the equation.
  2. Multiply the coefficients of each variable term by their exponents.
  3. Decrement of each exponent by one.
  4. Use new co-efficient and exponents in place of the old ones.
  5. Find the value of the function from the value of the variable.

So now we can easily find the derivative of a function by the above steps but getting it done with the help of code is a bit difficult task. But don’t worry we are here for you always. Making your difficult tasks easier and getting them done in the most understandable way. So, moving further let’s dive into the code.


 #include <bits/stdc++.h> 
using namespace std; 

long long dTerm(string t1, long long v) 
  string coeffStr = ""; 
  int i; 
  for (i = 0; t1[i] != 'x'; i++) 
  long long coeff = atol(coeffStr.c_str()); 

  string powStr = ""; 
  for (i = i + 2; i != t1.size(); i++) 
  long long expo = atol(powStr.c_str()); 

  return coeff * expo * pow(v, expo - 1); 

long long dVal(string& poly, int v) 
  long long ans = 0; 

  istringstream is(poly); 

  string t1; 
  while (is >> t1) { 

    if (t1 == "+") 

      ans = (ans + dTerm(t1, v)); 
cout<<"The derivative of a function is "<< ans; 

int main() 
  string str = "2x^2 + 4x^1"; 
  int v = 2; 
  cout << dVal(str, v); 
  return 0; 



The derivative of a function is 12

Find k-th smallest divisor of a number in C++

How to prevent object copy in C++

Leave a Reply

Your email address will not be published. Required fields are marked *