I need to write a program using a for loop that displays a 2% increase over a period of five years. It must display the new amount for each year. Any help or guidance would be appreciated. Thank you.
#include <iostream>
using namespace std;
int main()
{
int tuit, projectTuit, n;
tuit = 6000;
for(n=1; n<=5; n++)
//Process
{
projectTuit = tuit * 1.02;
//Output
cout << projectTuit << '\n';
}
return 0;
}
/*
6120
6120
6120
6120
6120
Process returned 0 (0x0) execution time : 0.062 s
Press any key to continue.
*/
You run the loop 5 times, but you perform the same calculation every time through the loop. You must update the base price that you're going to be calculating a 2% increase toward.
#include <iostream>
usingnamespace std;
int main()
{
int tuition, projectedTuition;
tuition = 6000;
for(int n=1; n<=5; n++) //Process
{
projectedTuition = tuition * 1.02;
//Output
cout << projectedTuition << '\n';
//THIS IS WHAT WAS MISSING!!!
tuition = projectedTuition;
}
return 0;
}
Check out line 17. That's resetting the tuition variable to the amount that has the 2% increase. That way, next time through the loop, you'll have an updated value for tuition.
You can accomplish this in less space, with fewer variables, but this is an explicit demonstration of why your code isn't behaving the way you probably want it to.