Search code examples
javascriptfor-loopif-statementswap

using for loops to swap digits


using a for loop i have to write code to swap the 2nd and 3rd digit of a number given via user input in javascript.

for ( i = 0; i < entNum.length; i++) {
    if (i === 0) num2 = entNum[i];
    else if (i === entNum.length - 2) {
        newNum = newNum + num2;
        newNum = entNum[i] + newNum;
    }
    else newNum = newNum + entNum[i];
}
console.log("New number:" + newNum)

this is the code i was able to produce however this code swaps the 1st and 2nd digit in the number and i can't seems to alter the code in the way to target the 2nd and 3rd digit nor do i 100% understand for loops and if statements. so a detailed explanation would be useful.


Solution

  • Loop over the input string, concatenating each digit to the output string. Except if the index is 1 or 2, append the digit at the other index to swap them.

    let entNum = '123456';
    let newNum = '';
    for (let i = 0; i < entNum.length; i++) {
      let digit;
      if (i === 1) {
        digit = entNum[2];
      } else if (i == 2) {
        digit = entNum[1];
      } else {
        digit = entNum[i];
      }
      newNum += digit;
    }
    console.log("New number:" + newNum)