The for loop 2 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

The for loop 2

How to proceed? Task Complete the code to output the given expression 3 times. Sample Input Learning is fun! Sample Output Learning is fun! Learning is fun! Learning is fun! var expression = readLine(); //your code goes here for (; expression <= 3; expression++) {document.write(expression + "<br/>");}

11th Sep 2021, 4:55 AM
Nizwm Borgoyari
Nizwm Borgoyari - avatar
7 Answers
+ 4
The for loop has the following syntax: for (statement 1; statement 2; statement 3) {   // code block to be executed } Statement 1 is executed (one time) before the execution of the code block. Statement 2 defines the condition for executing the code block. Statement 3 is executed (every time) after the code block has been executed. Solution: for(var i=0;i<3;i++){console.log(expression)}
11th Sep 2021, 5:03 AM
SAN
SAN - avatar
+ 1
Thank you so much
11th Sep 2021, 5:05 AM
Nizwm Borgoyari
Nizwm Borgoyari - avatar
+ 1
Thank you SAN !!
15th Oct 2021, 12:02 PM
Anne Jungers
Anne Jungers - avatar
+ 1
for(var i=1; i<=3; i++){ console.log(expression); }
14th Sep 2022, 12:18 PM
ANKIT YADAV
ANKIT YADAV - avatar
0
I struggled a little bit with this at first. I tried this first this and it didn't work: for (; expression<3; expression++) { console.log(expression + "< /br>"); } Why? It looks like the given variable "expression" is just the string (text – but with the line break already defined). So no need to add a line break. But you do have to add: - a countable variable value (in my case test=0) which serves to put in a number to start the counting from - a condition (in my case test<3) to define how far to count/add, respectively to stop executing after 3 times - the counting function (in my case test++) which continuously adds one more. Then you define what is to be executed if (resp. as long as) the above conditions are or aren't met, and how you want this to be executed (logged to the console). Based on the above, my solution is: for (var test=0; test<3; test++) { console.log(expression); } Basically (take number 0 and don't stop adding 1 until you reached 3) {each time the above (adding 1) is executed, log the text variable "expression" to the console; stop after 3 times} (of course you could also start counting from, let's say 5 and count to 8 – doesn't matter)
22nd Nov 2021, 3:18 PM
Rapha
0
I was having a hard time with this also so i finally wrote: for(var i=1; i<=3; i++){ console.log("Learning is fun!");} it worked but now I can't go any further in the course and I don't know why.
23rd May 2022, 4:55 AM
D Ross
D Ross - avatar
0
var expression = readLine(); for(var i=0;i<3;i++) {console.log(expression) } IS CORRECT
26th Feb 2023, 6:15 PM
Rubén Rodriguez Pérez