I have a homework assignment which I feel I am close to getting right. The assignment is as follows:
Banks loan money to each other. In tough economic times, If a bank goes bankrupt it may not be able to pay back the loan. A bank's total assets is its current balance plus its loans to other banks. Figure 8.1 ( attached image ) is a diagram tat shows five banks. The banks' current balances are: 25, 125, 175, 75 and 181 million dollars, respectively. The directed edge from node 1 to node 2 indicates that bank 1 loans 40 mill to bank 2.
If a banks total asset is under a certain limit, the bank is considered unsafe. If a bank is unsafe, the money it borrowed cannot be returned to the lender and the lender cannot count the loan in its total assets. Consequently, the Lender may also be unsafe.
Write a program to find all unsafe banks. Your program reads the input as follows. It first reads two integers, n and limit, where n indicates the number of banks and limit is the minimum assets for keeping a bank safe. It then reads n lines that describe the information for n banks with id from 0 to n-1. The first number in the line is the bank's balance. The second number indicates the number of that borrowed money from the bank, and the rest are pairs of two numbers. Each pair describes a borrower. The first number is the banks id and the second number is how much it borrowed. Assume that the maximum number of banks is 100. For example, the input for the five banks is as follows ( the limit is 201)
5 201
25 2 1 100.5 4 320.5
125 2 2 40 3 85
175 2 0 125 3 75
75 1 0 125
181 1 2 125
The total assets of bank 3 is 75 plus 125 which is under 201 so the bank is unsafe. After bank 3 is unsafe the total assets of bank 1 becomes 125 + 40 and is now also unsafe. The output should be "Unsafe banks are 3 1"
This is my current solution to the problem. I can't figure out how to get it to find all the unsafe banks. Just the first one. I have it set to take static input for testing. I have the working user input code ready to go if I can just get it to work properly.
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 100;
double balance[SIZE];
double loan[SIZE][SIZE];
int nobanks;
int limit;
int i = 0;
int j = 0;
int k = 0;
int noborrowers;
double assets[SIZE];
bool isSafe[SIZE];
bool newunsafefound = true;
cout << "Enter number of banks and the limit:" << endl;
// Set all of the data
nobanks = 5;
limit = 201;
balance[0] = 25.0;
balance[1] = 125.0;
balance[2] = 175.0;
balance[3] = 75.0;
balance[4] = 181.0;
loan[0][1] = 100.5;
loan[0][4] = 320.5;
loan[1][2] = 40.0;
loan[1][3] = 85.0;
loan[2][0] = 125.0;
loan[2][3] = 75.0;
loan[3][0] = 125.0;
loan[4][2] = 125.0;
// Set array to all true values
for(i = 0; i < nobanks; i++)
{
isSafe[i] = true ;
}
cout << "Unsafe banks are: ";
i=0;
while(isSafe[i] == true)
{
newunsafefound=false;
i=0;
do
{
assets[i] = balance[i]; //Set assets to balance
for (j = 0; j < nobanks; j++) // Check if a bank has loans and add them to assets
{
if (loan[i][j] >= 0)
assets[i] += loan[i][j];
}
if (assets[i] < limit) // Check to see if current bank meets limit
{
isSafe[i] = false; // Set bank to not safe if limit not met
newunsafefound = true;
cout << i << " " ; //Display the bank that is unsafe and a space for the next bank
k=0;
for (k = 0; k < nobanks; k++)
{
loan[i][k] = 0; //Set banks loans to 0 if unsafe.
k++;
}
}
i++;
} while(i < nobanks);
}
return (0);
}
What am I doing wrong?
You have to explicitly initialize the loan array, so the elements you aren't using don't have arbitrary values:
double loan[SIZE][SIZE] = {{0}};
Also loan[i][k] = 0; means that you are zeroing the loan the bank i has given to the bank k, but what you want is to zero any money that the bank i has borrowed to the bank k.
And there is a problem:
in the exit condition of your outer loop (it would only exit if the last bank (nobank-1) was unsafe),
in the handling of newunsafefound which doesn't do what the variable name suggests.
for (k = 0; k < nobanks; k++)
{
loan[i][k] = 0; //Set banks loans to 0 if unsafe.
k++;
}
That extra increment for k looks very suspicious ;)
// Astrid Giraldo
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
int n; // number of banks
double limit; // Minimum total assets for keeping a bank safe.
System.out.println("Enter number of banks: ");
n = input.nextInt();
System.out.println("Enter minimum total assets to be a safe bank: ");
limit = input.nextDouble();
double[][] borrowers = new double[n][n];
double[] balance = new double[n];
int numBorrowers;
for (int i = 0; i < borrowers.length; i++) {
System.out.println("Enter the bank's balance");
balance[i] = input.nextDouble();
System.out.println("Enter number of borrowers from this bank");
numBorrowers = input.nextInt();
for (int j = 0; j < numBorrowers; j++) {
System.out.println("Enter borrower bank id and the amount borrowed: ");
borrowers[i][input.nextInt()] = input.nextDouble();
}
}
markUnsafeBanks(borrowers,balance, limit);
displayUnsafeBanks(borrowers, balance, limit);
}
public static double analizeUnsafeBanks(double[][] borrowers, double[] balance, int bankId) {
double sum = balance[bankId];
for (int i = 0; i < borrowers.length; i++) {
sum += borrowers[bankId][i];
}
return sum;
}
public static void setLoanToZero(double[][] borrowers, double[] balance, int unsafeBankId, double limit) {
for (int i = 0; i < borrowers.length; i++) {
if (borrowers[i][unsafeBankId] > 0) {
borrowers[i][unsafeBankId] = 0;
if ( unsafeBankId > i && analizeUnsafeBanks(borrowers, balance, i) < limit) {
setLoanToZero(borrowers, balance, i, limit);
}
}
}
}
public static void markUnsafeBanks(double[][] borrowers, double[] balance, double limit) {
for (int i = 0; i < borrowers.length; i++) {
if (analizeUnsafeBanks(borrowers, balance, i) < limit) {
setLoanToZero(borrowers, balance, i, limit);
}
}
}
public static void displayUnsafeBanks(double[][] borrowers, double[] balance, double limit){
for (int i = 0; i < borrowers.length; i++) {
double assets = analizeUnsafeBanks(borrowers,balance,i);
if ( assets < limit) {
System.out.println("Bank " + i + " is unsafe. It assets are " + assets);
}
}
}
Related
I have a C++ assignment which I've been working on in the last 2 weeks. My knowledge is very limited, as I just started learning C++ and algorithms in February.
The assignment is:
N number of guests were invited to a party. We know all guests arrival and leave time. We want to know which guest met the LEAST amount of other guests. Two guests meet when guest1_arrivaltime <= guest2_leavetime and guest2_arrivaltime <= guest1_leavetime. If there are multiple guests who met the same amount of other guests, only one needs to be printed out.
Use: standard input (cin, cout) and greedy algorithm.
N (number of guests) can range from 1 to 1 000 000, the arrival and leave time values can be between 1 and 100 000
Run time limitation: 0.1 second
Memory limitation: 32 MB
I have a working code which seems to be okay to me, but when I upload it to the school's server I only get 27 marks out of 100. I need 50 marks to pass.
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
struct guestData
{
int guestIndex;
int time;
guestData(int guestIndex, int time)
{
this->guestIndex = guestIndex;
this->time = time;
}
guestData()
{
guestIndex = 0;
time = 0;
}
};
int n;
guestData * arrive;
guestData * leave;
set<int> guestsIn;
set<int> * metSet;
int minGuests;
int minIndex = 1;
bool operator<(const guestData & l, const guestData & r)
{
return l.time < r.time;
}
void read(int n)
{
arrive = new guestData[n];
leave = new guestData[n];
metSet = new set<int>[n];
minGuests = n;
for (int i = 0; i < n; ++i){
int arriveTime;
int leaveTime;
cin >> arriveTime >> leaveTime;
arrive[i] = guestData(i, arriveTime);
leave[i] = guestData(i, leaveTime);
}
}
void process()
{
sort(arrive, arrive+n);
sort(leave, leave+n);
int i = 0, j = 0;
while (i < n && j < n)
{
if (arrive[i].time <= leave[j].time)
{
int currentTime = arrive[i].time;
int in = arrive[i].guestIndex;
for (auto it = guestsIn.begin(); it != guestsIn.end(); ++it)
{
metSet[in].insert(*it);
metSet[*it].insert(in);
}
guestsIn.insert(in);
i++;
}
else
{
int currentTime = leave[j].time;
int out = leave[j].guestIndex;
guestsIn.erase(out);
j++;
}
}
}
void findMin(){
for (int i = 0; i < n; ++i)
{
if (metSet[i].size() < minGuests)
{
minGuests = metSet[i].size();
minIndex = i+1;
}
}
}
int main()
{
cin >> n;
read(n);
process();
findMin();
cout << minIndex << " " << minGuests;
return 0;
}
The problem: it works great on the example input, which is:
8
1 3
4 8
9 12
2 5
3 9
7 10
2 3
1 3
where 8 is the n (number of guests) and then 8 x the arrival(left row) and leave time(right row) for the guests.
The output for this example input is: 3 2 which is correct, because the 3rd guests met the least amount of other guests (2)
However, I get this error on my school's website when I upload my code: ERROR CODE 11 ILLEGAL MEMORY REFERENCE
You should free the memory at the end of the program. The grading system probably detects you are not doing that.
delete[] arrive;
delete[] leave;
delete[] metSet;
I'm writing a program in C++ where the inputs are N (the number of villages/rows), M (the number of days/columns) and an H[N][M]
matrix where I individually input the temperatures (min -50, max 50).
The output should be the total number of days when the village with the lowest
temperature has the highest forecast temperature, and after that the number (column) of these days in ascending order.
So if I input something like this:
3 5
10 15 12 10 10
11 11 11 11 20
12 16 16 16 20
The output should be:
2 2 3
Or input:
3 3
1 2 3
1 2 3
1 2 3
Output:
2 1 2
My approach was to first store the minimum temperatures and maximum forecast temperatures of each day into two separate arrays and
then writing a for loop where I check each village day by day if they contain both the minimum value on the given day and maximum forecast temperatures from that day on.
I have the following code:
#include <iostream>
const int maxarr = 1000;
int H[maxarr][maxarr];
using namespace std;
void read(int N, int M, int t[maxarr][maxarr]);
void count(int N, int M, int t[maxarr][maxarr]);
int main()
{
int N;
int M;
cout<<"Number of villages? ";
cin>>N;
cout<<"Number of days? ";
cin>>M;
read(N,M,H);
count(N,M,H);
return 0;
}
void read(int N, int M, int t[maxarr][maxarr])
{
for(int i = 0; i < N ; i++)
{
for(int j = 0; j < M ; j++)
{
cin>>t[i][j];
}
}
}
void count(int N, int M, int t[maxarr][maxarr])
{
int mintemparr[maxarr];
int maxtemparr[maxarr];
int mintemp;
int maxtemp;
int days[maxarr];
int cnt = 0;
for(int j = 0; j<M; j++)
{
mintemp = 51;
for(int i = 0; i<N; i++)
{
if(t[i][j]<mintemp)
{
mintemp = t[i][j];
}
mintemparr[j] = mintemp;
}
}
for(int i = 0; i < M-1; i++)
{
maxtemp = -51;
for(int j = 0; j < N; j++)
{
for(int k = i+1; k < M; k++)
{
if(t[j][k]>maxtemp)
{
maxtemp = t[j][k];
}
}
maxtemparr[i] = maxtemp;
}
}
for(int i = 0; i < M-1; i++)
{
for(int j = 0; j < N; j++)
{
for(int k = i+1; k < M; k++)
{
if(t[j][i] == mintemparr[i])
{
if(t[j][k] == maxtemparr[i])
{
days[cnt] = i+1;
cnt++;
//tried an i++ here, didn't work as intended
}
}
else
{
j++;
}
}
}
}
cout<<cnt<<" ";
for(int i = 0; i < cnt; i++)
{
cout<<days[i]<<" ";
}
}
There are some instances where it works perfectly, for example with the first input it's output is as it should be. But with the
second input I get
6 1 1 1 2 2 2
and a longer (1000x1000) input, which I obviously can't copy here also gives wrong results.
How could I make this code work as intended?
The reason why you're getting 6 1 1 1 2 2 2 for the second example is that you're not stopping to check whether a particular day fulfils the condition once you have found that it does. Thus you find that on day 1 the condition is fulfilled for village 1, village 2 and village 3 (the first three 1s in the result), and then the same happens for day 2.
From the comment
tried an i++ here, didn't work as intended
I guess you already identified that problem and the i++ was intended to prevent rechecking the same day again. However, as you noticed, that alone doesn't work - the reason here is that when skipping ahead to the next day you need to ensure that for that day checking the condition again starts with village 1 and the search for the highest temperature needs to begin from the start as well.
To do so, just add
++i; // carry on with the next day
j = 0; // start with the first village in the next iteration
k = i; // search for the highest temperature beginning from day i + 1
// note that at the end of the loop body `k` will be incremented
// so we need to use `k = i` instead of `k = i + 1` as in the loop-initializer here.
after cnt++ in place of the comment I quoted above.
With this change one gets the output you described in the question for both cases, as you can see here.
Given the input you uploaded to zippyshare I believe that the output for the second example should indeed be 3 1 2 3 instead of 2 1 2. Luckily the code is easy to change to accomodate that: Just replace all k = i + 1s by k = i and change the newly added k = i to k = i - 1 so that searching for the highest forecasts includes the present day.
Apparently I was actually suppose to create an array that randomly assigns birthdays over many trials (5000). It's then suppose to count up each time there is at least 2 birthdays for 2 - 50 people and divide the outcome by 5,000 to get the approximate probability. I believe I have my loops messed up and would like some feedback. Not code, I would like to understand exactly what is going wrong and how I messed it up.
int main()
{
const int trials(5000);
double total;
int count(0), birthdays[49];
srand(time(NULL));
for (int i = 2; i <= 50; i++)
{
for (int k = 0; k < trials; k++)
{
fillUp(birthdays, 49);
for (int j = i + 1; j <= 50; j++)
{
if (birthdays[i] == birthdays[j])
{
count += 1;
}
}
}
total = count / 5000.0;
cout << "For " << i << " the probability is " << total << endl;
}
return 0;
}
void fillUp(int birthdays [], int size)
{
for (int i = 0; i < size; i++)
{
birthdays[i] = rand() % 365 + 1;
}
}
Output:
For 2 the probability is 0.1286
For 3 the probability is 0.2604
...
...
For 49 the probability is 3.9424
For 50 the probability is 3.9424
Any help would be really appreciated.
The problem isn't the C++ code; you just have a typo in your math. It should be:
power = (num * (num - 1.0) / 2.0);
chance = 1.0 - pow(constant, power);
You are calculating 364/365 ≈ 0.0027 to the power of some large number, which results in a number only very slightly above zero. When rounded to the requested output precision, this results in zero.
You may know the formula, but your code is not implementing it correctly. Here is some C code that implements the formula correctly:
#include <stdio.h>
int main(void) {
double p;
int ii;
int people;
for (people = 3; people < 50; people++) {
p = 1;
for (ii = 1; ii < people; ii++) {
p *= (365.0 - ii) / 365.0;
}
printf("for %d people, probability is %.4f\n", people, 1 - p);
}
return 0;
}
This results in the following output:
for 1 people, probability is 0.0000
for 2 people, probability is 0.0027
for 3 people, probability is 0.0082
for 4 people, probability is 0.0164
for 5 people, probability is 0.0271
for 6 people, probability is 0.0405
for 7 people, probability is 0.0562
for 8 people, probability is 0.0743
for 9 people, probability is 0.0946
for 10 people, probability is 0.1169
for 11 people, probability is 0.1411
for 12 people, probability is 0.1670
for 13 people, probability is 0.1944
for 14 people, probability is 0.2231
for 15 people, probability is 0.2529
for 16 people, probability is 0.2836
for 17 people, probability is 0.3150
for 18 people, probability is 0.3469
for 19 people, probability is 0.3791
for 20 people, probability is 0.4114
for 21 people, probability is 0.4437
for 22 people, probability is 0.4757
for 23 people, probability is 0.5073
for 24 people, probability is 0.5383
for 25 people, probability is 0.5687
for 26 people, probability is 0.5982
for 27 people, probability is 0.6269
for 28 people, probability is 0.6545
for 29 people, probability is 0.6810
Leading to the familiar result that "the chance is > 50% with just 23 people".
In essence you have created a new question, so I will create a new answer. Right now you keep changing the birthdays while you are looping over them; this is why things don't work. You need two nested loops to test for equal birthdays (or if you are smart you sort them, then only check adjacent ones. It is probably faster with n = 50.)
You also need to start testing at the first birthday (your array is base 0 - but you start with i = 2). And for each trial, you can see how many people you need to compare before you have a match. The correct code will look something like this (note that I run 5000 trials for each number of people in the room; you could be more efficient by checking for a match when you have 3,4,5... people based on the same sample, but then there would be some correlation in the sampling).
EDITED - tested this code, seems to compile and run OK. Results look close to expected values.
#include <iostream>
void fillUp(int birthdays [], int size)
{
for (int i = 0; i < size; i++)
{
birthdays[i] = rand() % 365 + 1;
}
}
int main(void) {
int birthdays[50];
int trials = 5000;
int flag;
double total;
int collisions[50];
// number of people "in the room"
for (int i = 2; i < 50; i++)
{
collisions[i] = 0;
// do 5000 trials:
for (int t = 0; t < trials; t++)
{
fillUp(birthdays, i);
flag = 0;
// compare all pairs (j,k):
for (int j = 0; j < i - 1 && flag == 0; j++)
{
for (int k = j + 1; k < i && flag == 0; k++ )
{
if (birthdays[k] == birthdays[j])
{
collisions[i]++;
flag = 1;
}
}
}
}
total = collisions[i] / 5000.0;
std::cout << "For " << i << " people in the room the probability is " << total << std::endl;
}
return 0;
}
Note - I did not have a chance to compile / test this; it should be right "in essence". Let me know if it gives a problem.
im doing an assignment on c++ and im stuck on how i would add a new transaction to my work, with a user defined numShares, and pricePerShare.
i have a transaction struct which looks like this:
struct Transaction
{
string stockSymbol; // String containing the stock symbol, e.g. "AAPL"
string buyerName; // String containing the buyer's name e.g. "Mr Brown"
int buyerAccount; // Integer containing an eight digit account code
int numShares; // Integer containing the number of sold shares
int pricePerShare; // Integer containing the buy price per share
};
this is the buildTransaction class:
static Transaction* buildTransactions(int numTransactions)
{
int maxShareVolume = 100000;
int maxSharePrice = 1000;
Transaction *transactions = new Transaction[numTransactions];
for(int idx = 0; idx < numTransactions; idx++)
{
transactions[idx].stockSymbol = pickRandomStockSymbol();
std::string buyerName = pickRandomBuyer();
transactions[idx].buyerName = buyerName;
transactions[idx].buyerAccount = lookupBuyerAccount(buyerName);
transactions[idx].numShares = 1 + rand() % maxShareVolume;
transactions[idx].pricePerShare = 1 + rand() % maxSharePrice;
}
return transactions;
}
how would i use that to add data to the transactions array using this:
void Analyser::addTransactions(Transaction* transactions, int numTransactions)
i would assume from this that all i would really need to have as user input would be the amount of shares, and the price per share, but that the other information fills itself in automatically, from choosing from the arrays.
instead of using arrays, you should use vectors.. the buildTransactions would be written this way:
std::vector<Transaction> buildTransactions(int numTransactions)
{
int maxShareVolume = 100000;
int maxSharePrice = 1000;
std::vector<Transaction> transactions;
for(int idx = 0; idx < numTransactions; idx++)
{
Transaction t;
t.stockSymbol = pickRandomStockSymbol();
std::string buyerName = pickRandomBuyer();
t.buyerName = buyerName;
t.buyerAccount = lookupBuyerAccount(buyerName);
t.numShares = 1 + rand() % maxShareVolume;
t.pricePerShare = 1 + rand() % maxSharePrice;
transactions.push_back(t);
}
return transactions;
}
by editting the buildTransactions function, you can easily add more data by doing this to your addTransactions function:
void Analyser::addTransactions(std::vector<Transaction> &transactions, int numTransactions)
{
for(int idx = 0; idx < numTransactions; idx++)
{
Transaction t;
t.stockSymbol = pickRandomStockSymbol();
std::string buyerName = pickRandomBuyer();
t.buyerName = buyerName;
t.buyerAccount = lookupBuyerAccount(buyerName);
std::cout << "Enter number of shares for transaction: ";
std::cin >> t.numShares;
std::cout << "Enter price per share for transaction: ";
std::cin >> t.pricePerShare;
transactions.push_back(t);
}
}
hope it helps :)
you can get amount of shares, and the price per share as inputs in a loop in addTransactions() method like the following:
for(int idx = 0; idx < numTransactions; idx++)
{
transactions[idx].stockSymbol = pickRandomStockSymbol();
std::string buyerName = pickRandomBuyer();
transactions[idx].buyerName = buyerName;
transactions[idx].buyerAccount = lookupBuyerAccount(buyerName);
ctd::cout<<"Enter number of shares for transaction "<<idx+1<<std::endl;
std::cin>>transactions[idx].numShares;
ctd::cout<<"Enter price per share for transaction "<<idx+1<<std::endl;
std::cin>>transactions[idx].pricePerShare;
}
//amt = amount of cents to get change for
//onhand = array of available coins . Ex: {3, 0, 1, 0} = 3 quart, 0 dime, 1 nickel, 0 pennies
//denoms = {25, 10, 5, 1}
//ndenoms = 4 ; i.e the number of different denominations
// thechange = array of change. Ex: if amt = 80, then one possible thechange = {3, 0, 1, 0} b/c 3*25 + 1*5 = 80 cents
int i = 0;
void makechange(int amt, int *onhand, int *denoms, int ndenoms, int *thechange)
{
if ( (denoms[i] * onhand[i]) > amt)
{
onhand[i]--; // # of coins is too much, decrement and try again
makechange(amt, onhand, denoms, ndenoms, thechange); // try agan
}
thechange[i] = onhand[i]; //found #of coins
amt = amt - denoms[i]*onhand[i]; // get remaining amount from change
i++;
if (amt != 0) // we're not done with change so move on to next denomination
{
makechange(amt, onhand, denoms, ndenoms, thechange);
}
else if (amt == 0) // we're done with the change so all the other # coins = 0
{
for (int j = i; j < amt; j++)
{
thechange[j] = 0;
}
}
}
Now, down in main when I actually call the function prototype and print out the result
//
makechange(amt, onhand, denoms, ndenoms, thechange);
for (int k = 0; k < ndenoms; k++)
{
cout << thechange[i] << " ";
}
//
I get an error.
This algorithm seems seems sensible to me, does anyone know why it keeps crashing, though?
Have I properly used recursion here?
If you call makechange twice, the second time it won't work because the global variable i will be wrong.
Also what should happen if you try to makechange and don't have enough change on hand to make it?
Similarly what happens if you have 3 quarters and 3 dimes, and are asked to make 80 cents in change? Your algorithm will use all 3 quarters and then get stuck.
did you mean
for (int k = 0; k < ndenoms; k++) { cout << thechange[k] << " "; }
a little typo made possible by the use of global variable i.
also
for (int j = i; j < amt; j++) { thechange[j] = 0; }
I think you meant
for (int j = i; j < ndenoms; j++)
depending on the final value of amt, this will cause you to run off the end of the array, resulting in a crash.
you can solve this more easily without recursion. are you required to use recursion for an assignment? if not, try this:
int makechange(int amt, int *onhand, int *denoms, int ndenoms, int *thechange)
{
for (int i=0; i < ndenoms && amt > 0; i++)
{
while (onhand[i] > 0 && denoms[i] <= amt)
{
onhand[i]--; // use one coin
thechange[i]++;
amt -= denoms[i];
}
}
return amt; // this is the amount you owe if you dont have enough on hand
}
I made the changes as mentioned by shsmith and here is the modified and complete c++ program.
#include <iostream>
using namespace std;
int i = 0;
void makechange(int amt, int *onhand, int *denoms, int ndenoms, int *thechange)
{
if ( (denoms[i] * onhand[i]) > amt)
{
onhand[i]--; // # of coins is too much, decrement and try again
makechange(amt, onhand, denoms, ndenoms, thechange); // try agan
}
thechange[i] = onhand[i]; //found #of coins
amt = amt - denoms[i]*onhand[i]; // get remaining amount from change
i++;
if (amt != 0) // we're not done with change so move on to next denomination
{
makechange(amt, onhand, denoms, ndenoms, thechange);
}
else if (amt == 0) // we're done with the change so all the other # coins = 0
{
for (int j = i; j < ndenoms; j++)
{
thechange[j] = 0;
}
}}
int main(){
//Now, down in main when I actually call the function prototype and print out the result
int amt = 80, onhand[] = {3, 0, 1, 0}, denoms[] = {25, 10, 5, 1}, ndenoms = 4, thechange[4];
makechange(amt, onhand, denoms, ndenoms, thechange);
for (int k = 0; k < ndenoms; k++)
{
cout << thechange[k] << " ";
}
cout << "\n";
return 0;}
This code is running perfectly on my machine. I compiled it using Cygwin.
Note: This algorithm would work only if you have the denomination coins more or correctly onhand. If there are insufficient number of coins onhand, then there is no exit for the recursive method because 'amt' would never become zero. At the same time, you never check for the 'i' value whether it is in bounds of the 'ndenoms'. This could also result in out of boundary errors which could cause ur program to exit incorrectly.