Skip to content Skip to sidebar Skip to footer

How Can I Use For Loop To Count Numbers?

I need to count numbers upward and have it print out with a string 'then' in between: 5 then 6 then 7 then... like this. I am very confused with using the parameters vs function na

Solution 1:

I would do something like this:

function countSheep(limit){
    for (var i = 1; i < limit; i +=1){
        console.log(i + " sheep")
    }
}

countSheep(10);

I used "sheep" instead of "then", but you get the idea. Since you just want to produce a side effect (print out a "1 then 2.." to the console, you don;t need to build up a string and then have your function return it.

If you did want to build up a string and then have your function return it though, you could do something like this instead:

functioncountSheep(limit){

    var allMySheep = "";

    for (var i = 1; i < limit; i +=1){
        allMySheep += (i + " sheep, ") 
    }

    return allMySheep;
}

console.log(countSheep(10));

Note: I started my loops at 1 (var i = 1) because I'm counting sheep, not numbers. You'd probably want to start yours at 0 (var i = 0).

Solution 2:

We can use JavaScript join function as well to achieve this Code

functiongetCountStr(count) {
    var str =[];
    for (var i = 1; i <= count; i++) {
        str.push(i);
    }
   console.log(str.join(' then '));
}  

Solution 3:

There are few issues with your code

functioncountUp(start) {
  start +=      // <<<<< what's this? It's an incomplete (and useless) statementfor(var i = start; i < start + 10; i++) {
    console.log(start[i] + "then");
    //          ^^^^^^^^ why are doing this? you should only write i
  }
  return start; // you don't need to return anything
}

A cleaned and working version from your code

functioncountUp(start) {
  for(var i = start; i < start + 10; i++) {
    console.log(i + " then ");
  }
}

But this code will have an extra 'then' at the end like 1 then 2 then, so here's a code that will handle this

functioncountUp(start) {
  // a temporary array to store your numbersvar tmpArr = [];
  for (var i = start; i < start + 10; i++) {
    // store the count into the array
    tmpArr.push(i);
  }
  // display the count by putting ' then ' between each numbervar stringToDisplay = tmpArr.join(' then ');
  console.log(stringToDisplay);
  document.write(stringToDisplay);
}

countUp(1);

Post a Comment for "How Can I Use For Loop To Count Numbers?"