+ 2
How many times will the following for loop run?
for (var i = 1; i <= 5; i++) { i = f(i); } function f(x) { return x + 3; } Could anyone explain why it's 3 not 2 ?
14 odpowiedzi
+ 4
How did you get 3.
It will run 2 times. Just print i inside loop and check how many times it will print.
Edit: actually value will be print 2 times but for loop will run 3 times.
+ 4
Alaa Aldeen Shammr
Actually for loop will run 3 times but on 3rd time condition will return false because of 9 <= 5 so 3rd value will not be print.
+ 4
Solo
Yes cycle will execute twice but run 3 times and on 3rd time execution will get fail and will not print any value.
+ 3
I made a test in node with the code below, and it outputs 4 and 8
for (var i = 1; i <= 5; i++) {
i = f(i);
console.log(i);
}
function f(x) {
return x + 3;
}
+ 3
Alaa Aldeen Shammr, I'm glad you figured it out, it's a very simple cycle. To draw an analogy, it's like trying to walk through a closed door, just because you pulled the door handle doesn't mean you walked through it. There were three attempts, but only two cycles.
Successful coding!🖐️😎
+ 2
A͢J , the cycle will be executed only twice, the third time "i" will be equal not to 6, but to 9 and the cycle will be interrupted.
+ 1
A͢J
This is one of sololeaen challenges.
When I wrote 2 I got a wrong answer.
But chatgpt said 3.
That confused me
+ 1
From the screenshot answer 2 is like "How many numbers will get printed?".
While the question is asking how many time the loops will run, and it is 3 because it need the third loops to evluated a false expression.
I don't think the community challenge are all made correctly, and I come across a questionable challenge in python not too long ago.
+ 1
Sorry all, I was confused 😅
The question is correct.
But when you review the challenge, sololearn gives you the correct answer not the answer you inserted.
Maybe I didn't enter 2.
Sololearn is correct ✅, chatGPT is wrong ❌.
+ 1
It would be nice if sololearn allow us to see our answers as well, so we won't get confused next time.
+ 1
Because when the Loop begins with
I=1
It enters into loop
While entering it will call the function f()
Then the i become changed value.. like that way I think code will execute in 2 times Only...
0
How can i create image of the company
0
first --> i = 1
second --> from (i = f (i))=(i = i+3) and i = 4 after that from i++ --> i =5
thirt works because condition 5<=5 --> true, and i = i+3+1=9
3 times....