So while I was checking the values within my arrays, I noticed that my mat2
array is printing right the 1st time, but not for the 2nd time, 3rd time, etc... Also the 2nd, 3rd, etc.. time it prints, they're all the same.
Here's the code to better illustrate:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
int rows;
int cols = 2;
int i, j, k;
double value;
printf("Input number of data points: ");
scanf("%d", &rows);
printf("\n\n");
double matA[rows][cols];
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
printf("Input element at [%d][%d]: ", i, j);
scanf("%lf", &matA[i][j]);
}
}
double input;
printf("\nInput the x-value you are interpolating: ");
scanf("%lf", &input);
double mat1[rows - 1];
for(i = 0; i < rows; i++) {
j = 0;
mat1[i] = (matA[i + 1][j + 1] - matA[i][j + 1]) / (matA[i + 1][j] - matA[i][j]);
j++;
}
printf("\n");
for(i = 0; i < rows - 1; i++) {
printf("%.9lf\n", mat1[i]);
}
double mat2[rows - 2];
for(i = 0; i < rows; i++) {
j = 0;
mat2[i] = (mat1[i + 1] - mat1[i]) / (matA[i + 2][j] - matA[i][j]);
j++;
}
printf("\n");
// printing mat2 array for the first time
for(i = 0; i < rows - 2; i++) {
printf("%.9lf\n", mat2[i]);
}
double mat3[rows - 3];
for(i = 0; i < rows; i++) {
j = 0;
mat3[i] = (mat2[i + 1] - mat2[i]) / (matA[i + 3][j] - matA[i][j]);
j++;
}
printf("\n");
for(i = 0; i < rows - 3; i++) {
printf("%.9lf\n", mat3[i]);
}
// printing mat2 array multiple times after printing it the first time
printf("\n");
for(i = 0; i < rows - 2; i++) {
printf("%.9lf\n", mat2[i]);
}
printf("\n");
for(i = 0; i < rows - 2; i++) {
printf("%.9lf\n", mat2[i]);
}
printf("\n");
for(i = 0; i < rows - 2; i++) {
printf("%.9lf\n", mat2[i]);
}
// end of printing mat2 array multiple times
return 0;
}
So for example, I input the following:
4
8
1
9
4
10
5
11
10
9.2
This is the output that I get (how the code runs):
Input number of data points: 9.2
Input element at [0][0]: 8
Input element at [0][1]: 1
Input element at [1][0]: 9
Input element at [1][1]: 4
Input element at [2][0]: 10
Input element at [2][1]: 5
Input element at [3][0]: 11
Input element at [3][1]: 10
Input the x-value you are interpolating: 9.2
3.000000000
1.000000000
5.000000000
-1.000000000 // this is mat2 printing the first time, which is correct
2.000000000
1.000000000
0.105371901 // this is mat2 printing multiple times after printing it the first time
-0.520661157
0.105371901
-0.520661157
0.105371901
-0.520661157 // end of printing mat2 multiple times after printing it the first time
I wonder what's wrong with the code.