First things first, turn on warnings. C compilers normally don't give you warnings, it's generally -Wall to get the basics (not all). Once we do that...
test.c:17:36: warning: format specifies type 'int' but the argument has type 'double' [-Wformat]
printf("%d $%d\n", year, output);
~~ ^~~~~~
%f
That tells us you're passing a floating point number to printf but trying to treat it as an integer, so it's going to be translated to a string incorrectly. It needs to be.
printf("%d $%.2f\n", year, output);
%f for a floating point number, and the .2 means to only use two decimal places like money.
test.c:9:14: warning: expression result unused [-Wunused-value]
rate + 0.01;
~~~~ ^ ~~~~
2 warnings generated.
This one tells us that the rate is never incremented. It's added to, but never stored anywhere. Instead you want rate += 0.01.
Now it runs. Once. And it only reports on year 11.
The problem is your outer do/while loop is using year, but the for loop will end with the year at the threshhold, so it will immediately stop. Instead of using a do/while loop, which is rarely necessary, use another for loop.
Second problem is you're printing the output and year outside the year for loop. So you'll only ever get the result for the last year. If you want all the years, the print goes inside.
#include <stdio.h>
int main(void)
{
const double initial_loan = 1000.00;
for( double rate = 0.01; rate <= 0.10; rate += 0.01 ) {
double loan = initial_loan;
for (int year = 1; year <= 10; year++) {
loan += rate*loan;
printf("%d @ %.2f%% $%.2f\n", year, rate * 100, loan);
}
}
return 0;
}
Notice that I declare variables in the narrowest possible scope. This tells you when they're appropriate to be used, and avoids goofs like trying to use the year in the outer loop.
A lot of C material will be extremely conservative and tell you to declare all variables at the start of a function. This isn't necessary, and hasn't been for a long, long time. Though declaring variables in a for loop is a C99 thing, that part of C99 is very well supported.
rate + 0.01does nothing useful – Jean-François Fabre 1 hour agoprintfstatement should be inside the for loop. Also, check out the good answer by @Schwern – Rizzo 1 hour ago