Why is it that some loops are just giving single answer? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Why is it that some loops are just giving single answer?

I know I loop repeats something a number of time, where do we have one answer for some loops? Am referring to JavaScript To those of you who want an example, I came across this example today: Var x=1; for(;x<6; x+=2){ x=x*x; } document. write(x); //Ans is 11,why one value?

24th Jul 2019, 11:27 PM
Francis Woli
Francis Woli - avatar
9 Answers
+ 7
No idea without seeing your code.
24th Jul 2019, 11:35 PM
Sonic
Sonic - avatar
+ 7
I think you talk about the output of a code, you need to enter the value at the exit of the loop. You just need to identify the syntax and to be used with. 😌 I wish I helped you. 🙋‍♂️
25th Jul 2019, 12:30 AM
Bastien GERMANY
Bastien GERMANY - avatar
+ 6
if you console log loop accumulator value out of the loop thats also reason for it show your codes it will make it easy to explain.
25th Jul 2019, 3:52 AM
Danielov
Danielov - avatar
+ 3
can you show us an example of that loop?
24th Jul 2019, 11:32 PM
Pikachu
Pikachu - avatar
+ 3
A loop can return a list or array (only one) 🤔
25th Jul 2019, 3:29 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 3
In your code , it is a for loop with condition x<6 and next is increment x value by 2. var x=1 for (; x<6; x+=2) { x=x*x } document.write(x) Here first iteration it is checking condition that is x less than 6 , then incrementing its value by 2 , that is 1+2 is 3 next x=3*3 then x=9, in next iteration it skipping condition as x is greater than 6 and simply updating it by 2 that is 11. If you try by increasing value of x by 3 it will give output 19, like for(; x<6; x+=3)
25th Jul 2019, 7:27 PM
Anil
+ 1
Yes that's it Francis Woli
25th Jul 2019, 4:13 AM
Bastien GERMANY
Bastien GERMANY - avatar
0
If I understand you well, your are worried as to why your code is not displaying all your outputs. That is because the document.write(x) is outside the loop and so only the final value of the loop would be assigned to x after the loop. // Try this Var x=1; for(;x<6; x+=2){ x=x*x; document. write(x); }
26th Jul 2019, 11:53 AM
[H•e•a•t•h•e•n]
[H•e•a•t•h•e•n] - avatar
0
Put write statement inside loop
7th Aug 2019, 2:55 PM
Atharva Gharbude
Atharva Gharbude - avatar