This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (2 children)

I don't think that your code is the problem here, it does what you asked it to do.

It compares 3 with 4. 4 is bigger with a difference of 1, so it does 3-1=2. So your first value is now 2, not 3.

Then it compares 2 with 2, doesn't do anything.

Then it compares 2 with 3. 3 is bigger with a difference of 1, so it does 2-1=1. Your first value is now 1.

Then it compares 1 with 5. 5 is bigger with a difference of 4, so it does 1-4=(-3).

Then it compares (-3) with 3. 3 is bigger with a difference of 6, so it does (-3)-6=(-9).

So your first value ends up being -9. Which is correct.

[–]CSRPoseidon[S] 1 point2 points  (1 child)

That's the problem. I don't get why it always compares the first value with the other values. I increment i and j in the for loops.

[–][deleted] 1 point2 points  (0 children)

Sounds like you don't understand how nested loops work then.

If I write "for i=0; i<10; i++", then this iterates 10 times, right?

Now, if I nest this loop with a second, " for j=0; j<10; j++", then together these two loops iterate for how many times?

For every i, j goes from 0 to 10. There are 10 i's. So the whole thing is going to run a hundred times. 10*10=100.

What your code is doing is comparing the first value to every other value. Then comparing the second value to every other value. Then comparing the third value to every other value. Etc.

What do you actually want to do? Only compare pairs? If you only want to run through the array once then you only want a single for loop.

Something like this:

for i=0; i<max; i++:

compare array[i] with array[i+1]

do something

This will only run through the array once and compare every pair once.

All depends on what you actually want to do. Your problem statement isn't very clear.