0

I have some lines of code like this. can anyone explain for me why "while loop" does not stop. it is keeping shows the result more than the balance.

static void Main(string[] args) { const double balance = 303.91; const double phonePrice = 99.99; double a = 0; while (a < balance ) { a = a + phonePrice; } Console.WriteLine(a); Console.ReadLine(); } 
8
  • 3
    It does exactly what you have written. The loop ends when a is bigger than balance and then you print a who is bigger than balance. What did you expect to happen here? Commented May 15, 2016 at 20:21
  • thats because you aren't increment. basically a is always zero without ever going up. Commented May 15, 2016 at 20:21
  • It should run 3 times. Commented May 15, 2016 at 20:22
  • @Laurel but a is not const Commented May 15, 2016 at 20:23
  • I thought it should be less than the "balance"?. Commented May 15, 2016 at 20:23

2 Answers 2

3

It does exactly what you have written.
The loop ends when a is bigger than balance and then you print that a variable

If you expect to stop the loop BEFORE running out of money then you need to change the loop exit condition

static void Main(string[] args) { const double balance = 303.91; const double phonePrice = 99.99; double a = 0; // You don't want to run out of money, so check if buying // another phone will bankrupt your finances.... while ((a + phonePrice) < balance ) { a = a + phonePrice; } Console.WriteLine(a); // a = 299,97 Console.ReadLine(); } 
Sign up to request clarification or add additional context in comments.

Comments

1

you are checking the value after add so it add first then check if a greater than balanceor not so one time extra phoneprice is added with a. Make your while loop

while ((a + phonePrice) < balance) { a = a + phonePrice; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.