How would I use recursion to create an array of extra change($100, 50, 20, 10, 5, 1) MATLAB -


how correctly make recursive call within every if-statement change of money? im focusing on "change" variable.thanks

test case 1-------------------------------------------------------------------------------

<>> [change,flag] = makechangerecursive(2,100)

change =

50

20

20

5

2

1

flag =

1

my code following

function [change,flag] = makechangerecursive(cost,paid)  if > 0  flag = true;  elseif == 0  change = 0;  flag = true;  return  elseif cost > paid;  flag = false;  change = [];  warning('that''s not enough buy item.');  return end    if >= 100 

change = [change; makechangerecursive(cost,paid - change )];

    paid =paid-100;    elseif >= 50      change = [change; 50];     paid =paid-50;  elseif 

this continues dollar values.

let's take @ first case:

if >= 100    change = [change; makechangerecursive(cost,paid - change )];    paid =paid-100; elseif ... 

the first time call function, variable change doesn't have in it. in fact, never have in @ beginning of function call because don't pass in parameter or give value prior line. putting change on right-hand side of assignment give error.

but that's okay, because that's not want anyway. want build change beginning.

in addition, change list of values. want pass recursive calls single value, paid after updating value.

let's build step step:

if >= 100 

if true, want subtract 100 amount paid (what pass in recursive call) , add 100 our list of change. let's first part:

   paid = paid - 100; 

as said, want update paid first because we're going use value in recursive call, happens next, along adding our new change value list:

   change = [100; makechangerecursive(cost, paid)]; elseif ... 

and on remainder of change values. i'm sure can take care of rest of them yourself.


i noticed didn't assign value extra. might have been cut-and-paste error, need make sure have @ beginning of function.


Comments