Nolan Albert Nolan Albert - 2 months ago 12
C# Question

Windows Form App Crashing With While Loops

First of all I would like to apologize for the messy code. Currently in my freshman year of college and had a question neither myself or my friends could figure out. The problem asks to accept an input from the user for dollars and find how many twenties, tens, fives, and ones will add to the least number of bills. Building the solution causes no error, but once ran and data is input it crashes instantly. I tried using the debugger to no avail, as well as changing the code (adding 'if' 'then' statements, etc.) I'm generally new to 'while' loops, and coding in general, so if I am making a stupid mistake feel free to roast me.
Thank you in advanced!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Dollars
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void textBox1_TextChanged(object sender, EventArgs e)
{

}

private void btnFindDem_Click(object sender, EventArgs e)
{
int twenties;
int tens;
int fives;
int singles;
int totDollars;
int sub1;
int sub2;
int sub3;
int sub4;
totDollars = Convert.ToInt32(txtDollars.Text);
twenties = 0;
tens = 0;
fives = 0;
singles = 0;
sub1 = totDollars;
sub2 = totDollars;
sub3 = totDollars;
sub4 = totDollars;
lstOut.Items.Add("Total dollars = " + totDollars.ToString("c"));
while (totDollars >= 20)
{
sub1 = sub1 - 20;
twenties = twenties + 1;
}
while (totDollars >= 10)
{
sub2 = sub2 - 10;
tens = tens + 1;
}
while (totDollars >= 5)
{
sub3 = sub3 - 5;
fives = fives + 1;
}
while (totDollars >= 1)
{
sub4 = sub4 - 1;
singles = singles + 1;
}
lstOut.Items.Add("Twenties: " + twenties);
lstOut.Items.Add("Tens: " + tens);
lstOut.Items.Add("Fives: " + fives);
lstOut.Items.Add("Ones: " + singles);




}
}
}

Answer

You aren't adjusting the value of the variable you are using in the while loop conditions. This:

sub1 = totDollars;
sub2 = totDollars;
sub3 = totDollars;
sub4 = totDollars;
lstOut.Items.Add("Total dollars = " + totDollars.ToString("c"));
    while (totDollars >= 20)
        {
            sub1 = sub1 - 20;
            twenties = twenties + 1;
        }

should be

lstOut.Items.Add("Total dollars = " + totDollars.ToString("c"));
    while (totDollars >= 20)
        {
            totDollars = totDollars - 20;
            twenties = twenties + 1;
        }

and the similar change made to the other while loops