-1

This is practice for a separate larger program, just a little console output showing how many of certain values are used. For some reason if I set the final while num value to zero, it won't output anything in the console. If I set it to 20 it will output, count the hundreds and the 20's, but skips the fact that there is a 50 because the while value won't allow it to go below 20. I tried while num is >= to zero as well. At > zero or >=, I would expect it would count the 50 and output 4 100's, 1 50 and 0 20's. I arbitrarily set the while value to 10 and it still gave 2 20's and the hundreds, but set at 1 it didn't output again, same as when set to zero. Before I can incorporate the logic into the bigger program which has a lot more values and returns I imagine I'll need to understand where I'm failing. I looked into recursion and trackback algorithms and they were just a bit beyond where I'm at yet. I did wonder if I could use modulus too. That's off track tho, I'm most curious about why that while value won't allow itself to be set to greater than or greater than/equal to zero.

using System;

namespace dollars_back_test
{
   class Program
   {
      static void Main(string[] args)
      {
         int num = 450, hundos = 0, fifties = 0, twenties = 0;
         do
         {
            if (num > 100)
            {
               num -= 100;
               hundos++;
            }
            else if (num > 50)
            {
               num -= 50;
               fifties++;
            }
            else if (num > 20)
            {
               num -= 20;
               twenties++;
            }
         } while (num > 20);
         Console.WriteLine($"Dispensing {hundos} 100's, {fifties} 50's, {twenties} 20's.");
         Console.ReadLine();
      }
   }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Brian
  • 27
  • 7

1 Answers1

0

I'm not sure I correctly understand the issue, but I believe what your asking is why the while loop is not printing any 50's. This is because you are checking if number is bigger than 50, but since you subtract 100 four times the values shall be:

1st loop: num 450
2nd loop: num 350
3rd loop: num 250
4th loop: num 150
5th loop: num 50 --> explenation: number isn't larger than 50, it is >= 50, that's why it will continue with printing the num>20 two times until 10 remains. 
6th loop: num 30
7th loop: num 10

To solve this issue you can simply replace this:

num>50

by num>=50

if that's what you would like to see. Then it will print the 50's.

jetspiking
  • 304
  • 1
  • 5
  • the same applies for 100 and 20 as well – Gian Paolo Mar 01 '20 at 23:04
  • Yes! That's weird though, I tried that initially but must have had an error somewhere else. This does the trick though with the while (num > 0) is at zero. I got too wrapped up in the 'while' value. Thank you! (I can't upvote yet but this is where I was failing) – Brian Mar 01 '20 at 23:07