Search code examples
c++for-loopnested-loops

How can I fix my issue with my nested for loop program?


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;
}


Solution

  • 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