Cant get the postfix increment operator to work correctly for the cpop ?
After compiling and running it it displays the "next years population prediction in the spot for 2012.
...
#define SPOP 9870 /* Starting population for calculation */
#define PRCT .10 /* The annual percentage growth in population */
#define POP_MAX 30000 /* The maximum population to be reached */
int
main(void){
/* Variable declarations */
int cpop, /* current pop */
year; /* year */
/* display header for population */
printf(" POPULATION YEAR\n\n");
year = 2012;
/* Display the table */
for ( cpop = SPOP;
cpop <= POP_MAX ;
cpop++) {
cpop = cpop + cpop * PRCT;
}
/* calculate total year */
year = year - 2012;
/* Display total number of years */
printf("The total year it takes to reach a population in excess of 30000 is %d\n", year);
return(0);
}
That's likely because you are doing the next year calculation and printing it before you are incrementing the year... Try moving the cpop = line below the printf() line...
Also you are mainpulating cpop in your loop counter and in your calculations... this will give wrong answers.
Finally the calcluation itself can give you wrong answers...
cpop = cpop + cpop * PRCT; // 10 + 10 = 20 20 * 0.1 = 2
You should bracket the expression to control the order of evaluation...
cpop = cpop + (cpop * PRCT); // 10 * 0.1 = 1 10 + 1 = 11
Or you could write it as...
cpop += cpop * PRCT;
You might better write you loop like this...
year = 2012;
cpop = SPOP;
do
{
printf("%11c%d%4c%5d\n", ' ', cpop, ' ', year);
cpop += cpop * PRCT;
year++;
}
while (cpop < POP_MAX);
This eliminates double manipulations of the variable and exits when the max is reached.
If you are stuck using a for() loop ...
year = 2011;
for (cpop = SPOP; cpop < MAX_POP; cpop += cpop * PRCT)
{
year++;
printf("%11c%d%4c%5d\n", ' ', cpop, ' ', year);
}
Hope that helps...