fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int n;
  7. cout << "Enter number of data points: ";
  8. cin >> n;
  9.  
  10. double x[n], y[n][n];
  11.  
  12. // Input x values
  13. cout << "Enter x values:\n";
  14. for (int i = 0; i < n; i++)
  15. {
  16. cin >> x[i];
  17. }
  18.  
  19. // Input y values
  20. cout << "Enter y values:\n";
  21. for (int i = 0; i < n; i++)
  22. {
  23. cin >> y[i][0];
  24. }
  25.  
  26. // Difference table (nested loop)
  27. for (int j = 1; j < n; j++)
  28. {
  29. for (int i = 0; i < n - j; i++)
  30. {
  31. y[i][j] = y[i + 1][j - 1] - y[i][j - 1];
  32. }
  33. }
  34.  
  35. // Print difference table (optional)
  36. cout << "\nForward Difference Table:\n";
  37. for (int i = 0; i < n; i++)
  38. {
  39. for (int j = 0; j < n - i; j++)
  40. {
  41. cout << y[i][j] << "\t";
  42. }
  43. cout << endl;
  44. }
  45.  
  46. double value;
  47. cout << "\nEnter value to interpolate: ";
  48. cin >> value;
  49.  
  50. double h = x[1] - x[0];
  51. double p = (value - x[0]) / h;
  52.  
  53. double result = y[0][0];
  54. double term = 1;
  55.  
  56. // Forward interpolation calculation (another loop)
  57. for (int i = 1; i < n; i++)
  58. {
  59. term = term * (p - (i - 1)) / i;
  60. result += term * y[0][i];
  61. }
  62.  
  63. cout << "\nInterpolated value at x = " << value << " is: " << result << endl;
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Enter number of data points: Enter x values:
Enter y values:

Forward Difference Table:

Enter value to interpolate: 
Interpolated value at x = 6.95282e-310 is: 8.69103e-311