I'm trying to become more familiar with C (been working through the MIT Practical Programming in C course and K&R) so decided to write a simple command-line linear interpolator. You can feed it a vector (where missing values are represented by 0n) and it should print an interpolated vector. Any comments on style etc are much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NULLA "0n"
#define NULLF -1000
#define MAXLEN 1000
int main(int argc, char * argv[])
{
if(argc < 2)
{
printf("missing vector for interpolation\n");
return 1;
}
if(argc - 1 > MAXLEN)
{
printf("vector is too long\n");
return 2;
}
float start, end, delta; //bound values and change for interpolation
int num_nulls = 0; //number of nulls in a given interpolation range
float filled[MAXLEN]; //vector where we will put our values
int i, j; //indices, for argv[] and filled[] vectors, correspondingly
//we want all values in filled to be initalized to zero, to avoid junk vals
for(j = 0; j < MAXLEN; j++)
filled[j] = 0.;
//let's go through any initial nulls, which just get put back in
//to the vector, since we can't interpolate (no starting/ending values yet)
for(i = 1, j = 0; i < argc && strcmp(argv[i], NULLA) == 0; i++)
filled[j++] = NULLF;
//the meat of the interpolations take places in the remaing parts
//of the vector
for( ; i < argc; i++)
{
if(strcmp(argv[i], NULLA) != 0 && num_nulls == 0)
{
start = atof(argv[i]);
filled[j++] = start;
}
else if(strcmp(argv[i], NULLA) != 0 && num_nulls > 0)
{
end = atof(argv[i]);
delta = (end - start) / (1 + num_nulls);
while(num_nulls-- > 0)
{
start+=delta;
filled[j++] = start;
}
filled[j++] = end;
start = end; //we should be ready for another interpolation
num_nulls = 0;
}
else
num_nulls++;
}
//add in any trailing nulls, since interpolation can't be performed
while(num_nulls-- > 0)
filled[j++] = NULLF;
for(i = 0; i < j; i++)
{
if(filled[i] != NULLF)
printf("%.2f ", filled[i]);
else
printf("%s ", NULLA);
}
putchar('\n');
return 0;
}