Home > OS >  Execute the loop until the condition met
Execute the loop until the condition met

Time:10-17

I need this code to execute the loop until I get result 1. I want to make this code to calculate depending on the inputNum if inputNum is even, the inputNum is divided by 2 and if the inputNum is odd, then multiple by 3 and plus one. I have done this so far but I have lost how to loop this function the condition is until I get result 1 as final. I really need your help Please teach me

const inputNum = 5;

let i = inputNum;

while (i == 1) {
  calculateNum();
}

function calculateNum() {
  if (inputNum % 2 == 0) {
    console.log('Input number : '   inputNum   ' (even number!)');
    let result = inputNum / 2;
    console.log('Result: '   result);
  } else {
    console.log('Input number : '   inputNum   ' (odd number!)');
    let result = inputNum * 3   1;
    console.log('Result: '   result);
  }
}

CodePudding user response:

Put the while loop in your function.

let inputNum = 5;

function calculateNum(inputNum) {
  while(inputNum !== 1) {
    if (inputNum % 2 == 0) {
      console.log('Input number : '   inputNum   ' (even number!)');
      let inputNum = inputNum / 2;
      console.log('Result: '   inputNum);
    } else {
      console.log('Input number : '   inputNum   ' (odd number!)');
      let inputNum = inputNum * 3   1;
      console.log('Result: '   inputNum);
    }
  }
  return inputNum
}

calculateNum(inputNum)

CodePudding user response:

You need to return a result from calculateNum:

function calculateNum() {
  if (inputNum % 2 == 0) {
    console.log('Input number : '   inputNum   ' (even number!)');
    let result = inputNum / 2;
    console.log('Result: '   result);
    return result;
  } else {
    console.log('Input number : '   inputNum   ' (odd number!)');
    let result = inputNum * 3   1;
    console.log('Result: '   result);
    return result;
  }
}

Then in your loop capture (and test) the result:

while (i != 1) {
  i = calculateNum();
}

CodePudding user response:

Something like this?:

const inputNum = 5;

let i = inputNum;

while (i !== 1) {
  calculateNum();
}

function calculateNum() {
  if (i % 2 == 0) {
    console.log("Input number : "   i   " (even number!)");
    i = i / 2;
    console.log("Result: "   i);
  } else {
    console.log("Input number : "   i   " (odd number!)");
    i = i * 3   1;
    console.log("Result: "   i);
  }
}

result:

Input number : 5 (odd number!)
Result: 16
Input number : 16 (even number!)
Result: 8
Input number : 8 (even number!)
Result: 4
Input number : 4 (even number!)
Result: 2
Input number : 2 (even number!)
Result: 1

EDIT:

So the main issue with your code is that you don't update the value of i, so actually you have an endless loop.

Instead of using the result, update the value of i.

  • Related