0

I wrote greedy in more than one way (while loops, modulo) and then I tried a for loop which always gives 0 and I don't understand why! Below is the for loop, can any one tell me what is wrong with it?

for (i=change2; i==0; i=change2)
{
    if (change2>=25)
    {
        change2=change2-25;
        n=n+1;
    }
    else if (change2<25&&change2>=10)
    {
        change2=change2-10;
        n=n+1;
    }
    else if (change2<10&&change2>=5)
    {
        change2=change2-5;
        n=n+1;
    }
    else if (change2<5&&change2>=1)
    {
        change2=change2-1;
        n=n+1;
    }
}
1

I think the test condition in the for loop should be like this

for (i = change2 ; i > 0 ; i = change2)
{
     // do something here
}

because when you write i == 0, then the loop executes only when i is initialized 0, i.e.change2 is 0. However change2 possesses a positive value most of the times. Therefore, using i > 0, will do the work as it will iterate the loop till the change is non negative. Remember not to use i >= 0 because this will lead to an infinite loop as you don't have a escape condition when i is equal to 0.

2
  • That worked ! Thanks. Aug 9 '14 at 3:32
  • 1
    @MohamedAlaaEl-DinFathy Please remember to mark the answer as accepted if it helped you :) Aug 11 '14 at 22:43
0

Your for loop declaration is quite a mess (sorry), won't be better to use a while loop (while) change2 is higher than 0?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .