-1

The end of my program is supposed to show the amount of ways I can make change for a dollar using nickels, dimes, quarters, and fifty-cents. Whenever I run my program, it gives me a really huge number and I don't know why. It's supposed to be around 40 something ( I estimate) but instead whenever I run it I get like 2686964 ways. This is my program:

//Program to display the number of ways to make change for a dollar
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
 int nickels,dimes,quarts,fifcents,way;
 double totalCents;
 cout<<setw(8)<<"Nickels"<<setw(7)<<"Dimes"<<setw(9)<<"Quarters"<<setw(12)<<"Fifty-Cents"<<endl;
 for(nickels=0;nickels<=20;nickels++)
 {
  for(dimes=0;dimes<=10;dimes++)
  {
   for(quarts= 0; quarts<=4; quarts++)
   {
    for(fifcents = 0; fifcents <=2; fifcents++)
    {
    
        totalCents=(nickels*5)+(dimes*10)+(quarts*25)+(fifcents*50);
        if(totalCents==100)
        {
              cout<<setw(5)<<nickels<<setw(7)<<dimes<<setw(7)<<quarts<<setw(10)<<fifcents<<endl; 
            way++;    
        }
       }
      }
     }
    }
    cout<<"There are "<<way<<" ways to make change for a dollar using using nickels, dimes, quarters and fifty-cents."<<endl;
}
Phoenix
  • 335
  • 2
  • 9
Emm
  • 25
  • 6
  • "*It's supposed to be around 40 something*" — have you tried **roughly** doing it on paper? Turning groups of five ones in { 1, 1, 1, ... , 1, 1, 1 } to single fives, there are **20** ways. Similarly, there are **10** ways of changing { 1, 1, 1, ... , 1, 1, 1 } into tens, **5** ways to turn it into twenties, and **2** ways of turning it into fifties. That's 37 right there. 40 sounds **way** too low an estimate - I just showed how to do it with only two types of coins. – Wai Ha Lee Apr 24 '15 at 04:29
  • Not sure I understand why you chose to format your C++ code using HTML snippet tags – Lightness Races in Orbit May 08 '15 at 03:19

1 Answers1

1

You need to initialize way with 0, that means, assign 0 to it at the beginning of the program way = 0; uninitialized variables may contain any content when declared

Eduardo Wada
  • 2,606
  • 19
  • 31
  • What do you mean by initializing way with 0? Writing a for loop for way? – Emm Apr 24 '15 at 03:45
  • 1
    Aditionally, take a look at the answer to this other question http://stackoverflow.com/questions/6032638/default-variable-value it explains why your program actually had undefined behavior and could give different outputs for different executions over the same input – Eduardo Wada Apr 24 '15 at 04:10