Help for While Loop

getting infinite looping on this beast. beast. beast.

le code gets the amount of money from the User and puts into variable userChange.

I need to simultaneously subtract from userChange the amount and add to the dollars & cents variables everytime a subtraction is made, so i can determine what change to give back.

And im missing something here. i can't figure it out.

(btw this is not the way im doing it for class, just want to figure out how to do it this way first)


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
while(userChange > 0)
		if (userChange > 2000)
		{
			++dollars; 
			userChange = userChange-2000;	
		}
		else if (userChange > 1000)
		{
			++dollars; 
			userChange = userChange -1000;
		}
		else if (userChange > 500)
		{
			++dollars;
			userChange = userChange - 500;
		}
		else if (userChange > 100)
		{
			dollars = dollars + 1;
			userChange = userChange - 100;
		} 
		if (userChange > 25)
		{
			++quarters;
				userChange = userChange - 25;
			}
		if(userChange > 10)
			{
				++dimes;
			userChange = userChange - 10;
			}
		if(userChange > 5)
			{
				++nickels;
				userChange = userChange - 5;
			}
		if (userChange > 1)
			{
				++pennies;
				userChange = userChange - 1;
			}
It is infinite because you are using > instead of >=.

BTW, your code treats $20, $10, and $5 bills the same as a $1.

You would find it much simpler to extract the parts without a loop:

1
2
3
4
5
6
7
8
9
10
11
12
twenties = userChange / 2000;
userChange -= twenties * 2000;

tens = userChange / 1000;
userChange -= tens * 1000;

etc.

nickles = userChange / 5;
userChange -= nickles * 5;

pennies = userChange;

Hope this helps.
LOL bruv. I feel real stupid now.

I spent way too long on this, but aren't using loops cooler than just doing the maths outside of one?

I also get what you mean about treating all the dollars the same. mind=blown/salt
Having someone else look at code usually makes the writer feel stupid. :o/

In fact, I regularly embarrass myself by looking over stuff I wrote... and I think to myself, "self, what's wrong with you?"

So don't worry, you're doing fine. :o>
Topic archived. No new replies allowed.