gryzek
gryzek

Reputation: 557

Sort entered number - difference between FOR and WHILE

I have to write a code which sort digits in one entered number.

For example: input: 4713239 output: 1233479

It doesn't work properly when I enter repeating digits(like 33) when I have the last loop as FOR:

for(int j = 0; j < arr[i]; j++) // in this loop my output is: 123479.

When I change this loop from FOR to WHILE it works properly. It means:

while(arr[i]) // and the number is sorted correctly (1233479)

True be told, I don't know what is the difference between these operations in this code.

Why FOR loop doesn't work properly? Could somebody explain me this?

I wrote a code:

int sort(int arg)
{
  int var, score = 0;
  int arr[10] = {0};


  for(int i = 0; i < 10; i++)
    {
      var = arg % 10;
      arr[var]++;
      arg = arg / 10;
    }


  for(int i = 0; i < 10; i++)
    {
      for(int j = 0; j < arr[i]; j++) //while(arr[i]) --> works correctly
    {
      score = score * 10 + i;
      arr[i]--;
    }
    }
  return score;
}

Upvotes: 0

Views: 67

Answers (1)

Sven Nilsson
Sven Nilsson

Reputation: 1869

You modify both arr[i] and j, therefore the loop will end too fast when both are part of the comparison.

for(int j = 0; j < arr[i]; j++) // increase j, compare with arr[i]
{
  score = score * 10 + i;
  arr[i]--; // decrease arr[i]
}

Upvotes: 1

Related Questions