C program for Newton Raphson method with output

In this program, you will implement the Newton-Raphson method for finding the root of the nonlinear equations in the C Programming language. The Newton-Raphson method is also known as Newton Method. you can find the root of the equation by taking the initial guess value.

Program to find Newton-Raphson method by using for loop

#include <stdio.h>
#include <math.h>

//equation f(x)
float f(float x) {
  // change the equation for solving another problem
  return pow(x, 2) - 6;

//derivative of equation i.e f'(x)
float derivative(float x) {
  // write the derivative of your equation
  return 2 * x;

int main() {
  float x;
  int n, i;

  printf("Enter initial guess value: ");
  scanf("%f", &x);

  printf("Enter number of iterations: ");
  scanf("%d", &n);
  for (i = 1; i <= n; i++) 
    if (derivative(x) == 0) {
      // f'(x) should not be 0
      printf("Division by Zero is not allowed.");

    //Newton Raphson formula
    x = x - f(x) / derivative(x);

    // fabs() method will return positive value
    printf("\nIteration %d and value %f", i, fabs(x));

  printf("\n approximate root: %f \n", fabs(x));
  return 0;


Enter initial guess value: 1
Enter number of iterations: 5

Iteration 1 and value 3.500000
Iteration 2 and value 2.607143
Iteration 3 and value 2.454256
Iteration 4 and value 2.449494
Iteration 5 and value 2.449490
 approximate root: 2.449490

Working of Newton-Raphson method:

  • Take initial guess and number of iterations from user and store in variables x and n
  • Iterate for loop from 1 to n. inside for loop check derivative(x) is zero or not. if 0 then the Newton-Raphson method will get failed.
  •  x = x - f(x) / derivative(x) this is a formula of the Newton-Raphson method, it will calculate the root of an equation. For example, let's find the root of  x -6=0. if your initial guess will be 1 then f(x)=-2 and derivative(x)=2.
  • Substitute the above value in Newton-Raphson formula i.e x=1- (-2)/2. value of x becomes 2. now pass new value i.e 2 in f(2) and derivative(2), the function will return value and you will again substitute value in the newton formula. you will do this up to n time.
  • After for loop end, you will get your approximate root value.
Point to remember:

If your guess value is closer to the root the Newton-Raphson method will take less time otherwise it will calculate but take more time.