Write a C program to implement the Lagrange interpolation.

Algorithm:

Step 1. Read x, n
Step 2. for i = 1 to (n + 1) is steps of 1 do Read xi,fi end for {the above statements reads x,s and the corresponding values of f is}
Step 3. Sum = 0
Step 4. for i = 1 to (n + 1) in steps of 1 do
Step 5. Profvnc = 1
Step 6. for J = 1 to (n + 1) in steps of 1 do
Step 7. If (j ≠ i) then prodfunc = prodfunc X(x - xj) / (xi - xj) end for
Step 8. Sum = Sum + fi x Prodfunc {sum is the value of f at x} end for
Step 9. Write x, sum
Step 10. Stop

Flowchart:

Program:

#include<stdio.h>
#include<math.h>
main()
{
 float y, x[20], f[20], sum, pf;
 int I, j, n;
 printf(“enter the value of n”);
 scanf(“%d”, &n);
 printf(“enter the value to be found”);
 scanf(“%f”, &y);
 printf(“enter the values of xi’s & fi’s”);
 for(i = 0; i < n; i++)
 {
  pf = 1;
  for(j = 0; j < n; j++)
  {
   if(j != i)
   Pf *= (y - x[j])/(x[i] – x[j]);
  }
  sum += f[i] * pf;
 }
 printf(“\nx = %f ”, y);
 printf(“\n sum =%f ”, sum);
}

Input & Output:

enter the value of n 4
enter the value to be found 2.5
enter the values for xi’s & fi’s
1 1
2 8
3 27
4 64
X = 2.500000
sum = 15.625000