Answer:
See explaination for program code
Explanation:
program code below:
#include<stdio.h>
int main()
{
//file pointer to read from the file
FILE *fptr;
//array to store the years
int years[50];
//array to store the population
float population[50];
int n = 0, j;
//variables for the linear interpolation formula
float x0,y0,x1,y1,xp,yp;
//opening the file
fptr = fopen("njpopulation.dat", "r");
if (fptr != NULL)
{
//reading data for the file
while(fscanf(fptr, "%d %f", &years[n], &population[n]) == 2)
n++;
//prompting the user
int year = -1;
printf("Enter the years for which the population is to be estimated. Enter 0 to stop.\n\n");
while(year != 0)
{
printf("Enter the year (1790 - 2010) : ");
scanf("%d", &year);
if (year >= 1790 && year <= 2010)
{
//calculating the estimation
xp = year;
for (j = 0; j < n; j++)
{
if (year == years[j])
{
//if the year is already in the table no nedd for calculation
yp = population[j];
}
else if (j != n - 1)
{
//finding the surrounding census years
if (year > years[j] && year < years[j + 1])
{
//point one
x0 = years[j];
y0 = population[j];
//point two
x1 = years[j + 1];
y1 = population[j + 1];
//interpolation formula
yp = y0 + ((y1-y0)/(x1-x0)) * (xp - x0);
}
}
}
printf("\nEstimated population for year %d : %.2f\n\n", year, yp);
}
else if (year != 0)
{
printf("\nInvalid chioce!!\n\n");
}
}
printf("\nAborting!!");
}
else
{
printf("File cannot be opened!!");
}
close(fptr);
return 0;
}
OUTPUT :
Enter the years for which the population is to be estimated. Enter 0 to stop.
Enter the year (1790 - 2010) : 1790
Estimated population for year 1790 : 184139.00
Enter the year (1790 - 2010) : 1855
Estimated population for year 1855 : 580795.00
Enter the year (1790 - 2010) : 2010
Estimated population for year 2010 : 8791894.00
Enter the year (1790 - 2010) : 4545
Invalid chioce!!
Enter the year (1790 - 2010) : 1992
Estimated population for year 1992 : 7867020.50
Enter the year (1790 - 2010) : 0
Aborting!!