Print 5 times number 5 on screen

Asked

Viewed 1,442 times

1

I am practicing a javascript exercise that asks us to use the "for" function to repeat 5 times the number 5 on the screen. But they claim the code is wrong and I don’t know what I’m doing wrong:

function imprimir5vezes(){
  
  for(var i=0;i<5;i++) {
console.log(i)
  } 
}

In time, to check, what I have to write to the console to check the function is console.log(i) or console.log(print5 times)?

Thank you!

3 answers

2


Hey, how you doing? So the way you put it you will be printing the variable i , so it will not be the number 5 in the 5 prints, but will assume each time a value, from 0 to 4. The correct in this case would be

 function imprimir5vezes(){

  for(var i=0;i<5;i++) {
     console.log(5)
  } 
}

  • Hi Luan! Thank you very much!

  • It was nothing, and one more thing when post questions about exercises if you are doing on any platform try to specify it, so in case someone already knows what it is or has been through the same thing will be easier to answer.

1

Jsjsj, then, colleague you are printing the loop iterator, ie at each cycle it is incrementing, actually its function are giving something like this :

//0,1,2,3,4

Correct, to print 5 times the number 5 would be like this :

function função() {
    for ( var i = 0; i < 5; i++ ) { 
        console.log( 5 );
    }
}

I hope I’ve helped, good luck with your code lines

  • Thank you very much Micah!!

  • Dnd, just one question, is from Santander City?

0

In your code you are displaying the variable value i five times in the console, which will give you a sequence of:

0
1
2
3
4

Example

function imprimir5vezes(){
    for(var i=0;i<5;i++) {
        console.log(i)
    } 
}

imprimir5vezes();

That’s because if the value of i is less than 5 will be shown on console the value of i that is 0 and then it will increase 1 and then comes back and does the same procedure until you reach a point that 5 will not be less than 5, so the loop stops running. For what you want, just put one Number or a String representing the value 5 in the console.

Example

function imprimir5vezes(){
    for(var i=0;i<5;i++) {
        console.log(5)
    } 
}

imprimir5vezes();

So the result will look like your code, what changes is that each iteration of the loop for the value of i rather a value 5.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.