skip to Main Content

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.

4

Answers


  1. Usually you want to create functions for the things you make so you can reuse it. Here I’m converting your number into a string and then split it into an array, swap the digits and join back.

    function swap(val, x, y) {
        let arr = (val + "").split("");
        let tmp = arr[x];
        arr[x] = arr[y];
        arr[y] = tmp;
        return parseInt(arr.join(""));
    }
    
    console.log(swap(12345, 1, 2));

    If you really need a loop, then

    function swaps(input, x, y) {
        let arr = (input + "").split("");
        for (let index = 0; index < x.length; index++) {
            let tmp = arr[x[index]];
            arr[x[index]] = arr[y[index]];
            arr[y[index]] = tmp;
        }
        return parseInt(arr.join(""));
    }
    
    console.log(swaps(123456, [1], [2]));
    Login or Signup to reply.
  2. You don’t even need a loop. You can do this with a string representation of the number.

    //make sure v1 is before b2
    let str = "" + entNum;
    let char1 = entNum.charAt(v1);
    let char2 = entNum.charAt(v2);
    str = str.substr(0,v1) + v2 + str.substring(v1 + 1, str.length) + v1;
    entNum = parseInt(str);
    
    Login or Signup to reply.
  3. 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)
    Login or Signup to reply.
  4. Function to swap consecutive values from starting position in a string using a loop:

    console.log(swapNumbers(`1234567`, 1));
    console.log(swapNumbers(`1234567`, 4));
    
    function swapNumbers(str, atPpos){
      const nrs = str.split(``);
      for (let i=0; i< nrs.length; i+=1) {
        if (i == atPpos) {
          [nrs[i], nrs[i+1]] = [nrs[i+1], nrs[i]];
          break;
        }
      }
      return nrs.join(``)
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search