Home > Net >  How to stop in "Too big " to count number s
How to stop in "Too big " to count number s

Time:12-12

In the "Too big" scenario, there should be no counting behavior and the program should end immediately after printing the "Too big" message.

var num1 = prompt("Enter the first number"); 
var num2 = prompt("Enter the second number");

console.log("The result is");
var result = ((num1   num2)*2);{console.log(result);}

if (result < 20) {
  console.log("Too small");

  function countPrint(howMany){ 
    for ( var count = 1; count <= howMany; count  ){ 
      console.log(count);
    }
  }
}

countPrint(result);if (result > 20){
  console.log("Too big");
}

CodePudding user response:

Try return; or return false;

This should stop the code from executing

CodePudding user response:

var num1 = prompt("Enter the first number");
var num2 = prompt("Enter the second number");

console.log("The result is");
var result = ((num1   num2)*2);
//             ^! thise may be strings, should be converted to numbers
{ // why block body? There's no `if` or whatever 
  console.log(result);
}

if (result < 20) {
  console.log("Too small");

  function countPrint(howMany) {
    for (var count = 1; count <= howMany; count  ) {
      console.log(count);
    }
  }
}

countPrint(result);
// ^! Cannot find name 'countPrint'.
// function should be outside if
// function is called no matter what the result is

if (result > 20) {
  console.log("Too big");
}

CodePudding user response:

soon you enter the for loop, it will log all number from your specified 1 to howMany, so you need to do something inside the loop and not outside as you are trying to do...

in a for loop, you can use break to get out of the loop

    for (var count = 1; count <= howMany; count  ) {
      if (count > 20) break;
      console.log(count);
    }

here's an example

const countNumbers = (howMany, maxCount) => {
    console.log('starting counting to', maxCount);
    for (let count = 1; count <= howMany; count  ) {
      if (count > maxCount) {
        console.log('the counting %s is higher than the max %s', count, maxCount);
        break; // let's break out of the loop
      }
      console.log('counting ->', count);
    }
}

countNumbers(30, 10);

  • Related