Do-while Beginner Question

Hi there,

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.

Thank you for your time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 #include <iostream>
#include <string>
using namespace 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;
}
Declare char doAgain outside of the do loop, like this:

1
2
3
4
5
char doAgain;
do
{
//code here
} while ( doAgain == 'y' || 'Y' );


oh and, Welcome to the forums! ;)
Last edited on
Thank you, so easy to fix. Side question though - why doesn't it work if I declare it inside the loop?
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.
Topic archived. No new replies allowed.