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
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.
If you really need a loop, then
You don’t even need a loop. You can do this with a string representation of the number.
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.
Function to swap consecutive values from starting position in a string using a loop: