Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading