I'm new to the forums here so forgive me if there is some Code of Conduct I'm not following. I just needed help with my code, for I am, a beginner in programming and can usually figure out a problem, and have done do-while loops before but I can't understand why it's saying my char variable "doAgain" says it's undefined where I put my while condition for the do-while loop. As said before I've done do-whiles before and have never had an issue until now. If someone could help It'd be very helpful.
#include <iostream>
#include <string>
usingnamespace std;
//Declare function
double inflationRate(double firstItem, double oldPrice);
int main()
{
//Declare variables
do
{
double firstItem, oldPrice, rate;
char doAgain;
//Asks for user inputs
cout << "Enter the price of your first item" << endl;
cin >> firstItem;
cout << "Enter the cost of your item as it was one year ago from today " << endl;
cin >> oldPrice;
rate = inflationRate(firstItem, oldPrice);
//Decimal places
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
//Outputs
cout << "Your rate of inflation is %" << rate << endl;
cout << "If you'd like to do this program again for a different item press y" << endl;
cin >> doAgain;
}while(doAgain == 'y' || 'Y');
system("pause");
return 0;
}
//Function definition
double inflationRate(double firstItem, double oldPrice)
{
double percentage, difference;
percentage = firstItem - oldPrice;
difference = percentage / oldPrice;
return difference * 100;
}
why doesn't it work if I declare it inside the loop?
By creating variables inside loops, means their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop, in that case, char doAgain only exist in between these two curly brackets, sometimes this might be exactly what you want, declaring variables inside loops ensure their scope is restricted to inside the loop, anyways, this will make a lot more sense when you start learning more about what's so called scoping.