Search code examples
c#countdown

How to count down large payments with a loop with c#


I am trying to make my own countdown of the national debt using loop statements. I am still very new to programming so I am having a hard time figuring out how to make this loop. I want to display how long it will take to pay off the debt if $100,000,000 was paid each day. I would like to display the numbers of days and years, but my priority right now is the loop. So far I have this

namespace Count_Down_The_National_Debt
{
    class Program
    {
        static void Main(string[] args)
        {
            //step 1
            // use 19.9 trillion dollars 
            long national_debt = 19900000000000;
            // keep track of how many days and it years it takes to pay off the US National Debt
            int day = 0, years = 0;

I looked back at a simpler program I made that used loops, but it was for counting up and not down. This is what I made based on my past program;

int j = 0;
            Console.WriteLine("By 100 Millions ");
            while (national_debt > 0)
            {
                Console.WriteLine(j.ToString());
                j = j - 100000000;
            }

However, it just runs in an infinite loop until I close my program. Will I need a break of some kind, or do I need to completely rewrite my loop?


Solution

  • The accepted answer isn't very good in my opinion. A while loop that is dependent on incrementing/decrementing numbers usually means you should not use a while loop. A better way to handle this is to use a for loop (and to put it in a method so its resuable)

    private static void CalculatePayDownDays(long payPerDay, long nationalDebt)
    {
        long days = (long)Math.Ceiling((decimal)nationalDebt / payPerDay);
    
        for (long i = 1; i < days + 1; i++)
        {
            nationalDebt -= payPerDay;
            Console.WriteLine("Day {0}, New Balance: {1:c}", i, nationalDebt);
        }
    }
    

    Fiddle here

    EDIT

    For the pedantic among us, I slightly modified the method.