user14882773
user14882773

Reputation:

Why my loop code have different behaviour i++, ++i , i+1

Here how it should work

const myArr =[6,8,10,5];
function weSort(arr){
  let done = false;
  while(!done){
    done = true;
    for(let i = 0; i < arr.length; i++){
      if(arr[i]>arr[i+1]){
        done = false;
        [arr[i],arr[i+1]] = [arr[i+1],arr[i]]
      }
    }
  }
  return arr
}

console.log(weSort(myArr))

But if i change the i+1 to i++ it doesn't do anything because i++ is also 0.
i++ is post increment which means it will increment right after it done executing (CMIIW)

const myArr =[6,8,10,5];
function weSort(arr){
  let done = false;
  while(!done){
    done = true;
    for(let i = 0; i < arr.length; i++){
      if(arr[i]>arr[i++]){
        done = false;
        [arr[i],arr[i++]] = [arr[i++],arr[i]]
      }
    }
  }
  return arr
}

console.log(weSort(myArr))

But if i change the i++ to ++i shouldn't it work like the i+1 since ++i is pre-increment which will add first before got put inside [i]. So shouldn't it look like this?
let i = 0
arr[i]>arr[++i] === arr[0]>arr[1]

Like this code below (Note This Code cause infinite loop)

const myArr =[6,8,10,5];
function weSort(arr){
  let done = false;
  while(!done){
    done = true;
    for(let i = 0; i < arr.length; i++){
      if(arr[i]>arr[++i]){
        done = false;
        [arr[i],arr[++i]] = [arr[++i],arr[i]]
      }
    }
  }
  return arr
}

console.log(weSort(myArr))

Why it works differently than the first code snippet with i+1? and cause loop

if something not clear feel free to comment to ask for further info. I'm sorry for the bad grammar English is not my native i try to explain the best i could. Thank you.

Upvotes: 0

Views: 61

Answers (3)

Rick
Rick

Reputation: 1870

i++ (or ++i) should only be written one time. That increments the value. only do that once.

I think you want to avoid: arr[i]>arr[++i]

because now you are additionally incrementing i every time that check happens, which logically doesn't really make sense.

Upvotes: 0

Charlie
Charlie

Reputation: 23798

The reason is that both i++ and ++i and are self assigning. Both the expressions modify the value of the variable i.

In your first snippet, the i + 1 does not modify the value of i - but only generates a new value by adding 1 to the current value of i.

No modification to the loop variable is done there - therefore the loop is not affected.

Upvotes: 0

julien.giband
julien.giband

Reputation: 2619

i + 1 will do the calculation and return the result, leaving i untouched

i++ will return the value of i, then increment i (do i = i + 1)

++i will increment i (i = i + 1), then return its value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#arithmetic_operators

Upvotes: 3

Related Questions