I'm obviously new to c++ and am having trouble understanding for loops. For this problem, I have to create a program that allows a user to input a base salary and will calculate a 5% raise for 3 years. Then display the total salary after 3 years.
This is what I have so far.
#include <iostream>
usingnamespace std;
int main()
{
//declare variables
double baseSalary = 0.0;
int year = 0;
double raise = 0.0;
double salary= 0.0;
//calculate 5% raise per year for 3 years
for (year = 1; year <= 3; year +=1)
{
cout << "Enter your base salary: $";
cin >> baseSalary;
raise = baseSalary * .05;
cout << "Raise: $"<< raise << endl;
salary = baseSalary + raise;
cout <<"Total yearly salary: $"<< salary <<endl <<endl;
}
system ("pause");
return 0;
}
I have to keep entering the yearly salary but my professor wants us to only enter it once and have the loop do all of the work. I really just need to figure out how to display the total after 3 years (which I think is done outside of the for loop).
Thanks
You only need 1 double variable, not the 3 you have.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
for (year = 1; year <= 3; year +=1)
{
cout << "Enter your base salary: $"; // Place these two lines outside the loop
cin >> baseSalary; // Change this to salary
raise = baseSalary * .05;
cout << "Raise: $"<< raise << endl; // Just remove both of these lines
salary = baseSalary + raise; // Rewrite this as salary *= 1.05
// This translates to salary = salary * 1.05, which is the same as
// salary = salary + salary * .05, which is essentially what you had before
cout <<"Total yearly salary: $"<< salary <<endl <<endl; // Move this to outside of the loop
}
Thanks that worked perfectly. Now all I need to do is show the raise separately from the total salary for each of the 3 years as well as the overall total for the 3 years. The total salary should add up to $33,101.25. The raises should display $500, $525, and $551.25.
#include <iostream>
usingnamespace std;
int main()
{
//declare variables
int year = 0;
double raise = 0.0;
double salary= 0.0;
cout << "Enter your base salary: $";
cin >> salary;
//calculate 5% raise per year for 3 years
for (year = 1; year <= 3; year +=1)
{
raise = salary * 0.05;
salary *= 1.05;
cout <<"Raise: $" << raise <<endl;
cout <<"Total yearly salary: $"<< salary <<endl <<endl;
}
cout <<"Total yearly salary: $"<< salary <<endl <<endl;//this is supposed to show the total salary over the 3 years plus the raise. It should equal $33,101.25 but it just displays the third salary instead of totaling them all.
system ("pause");
return 0;
}