0
Is for loop better than while loop?
I was solving a problem on hackerearth.com. My solution takes 1.1 second and gave TLE. When I replaced while loop with for it got accepted. It also got accepted when i replace var-- with --var>=0 in while loop condition. So, is for loop better than while? Or post decrement is slower than pre decrement?
5 Answers
+ 5
The performance is the same. The big difference is in the actual ease of coding. Also with the for loop you have better control of your variables and there is less chance of creating global variables that will cause your program to fail. I did this lesson yesterday https://code.sololearn.com/WOS0rq2Z66fG/?ref=app
+ 3
The for loop is the more modern acceptable way according to Codetrain. As for pre decrement and post decrement they are apples and pears. Meaning they are not even similar.
+ 2
Donna Output of your first loop is incorrect. It will be 01234. After first condition check, body of loop gets executed before increment.
PS: I'm familiar how for and while loop works. I'm just curious if performance wise one is better than other or not.