{ For Loop } Why it is so tricky and confusing. Can some one give a simple explanation. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

{ For Loop } Why it is so tricky and confusing. Can some one give a simple explanation.

for loop explanation

29th Mar 2018, 7:21 PM
Varshilov Nikolay
Varshilov Nikolay - avatar
3 Answers
+ 3
int i = 0; while(i < 10) { // code ++i } is (almost) the same as: for(int i = 0; i < 10; ++i) { //code } The variable i in the for loop is a local variable in this example, which means that it gets "deleted" when the loop ends. The variable i declared before the while loop will stay.
29th Mar 2018, 7:25 PM
Chris
Chris - avatar
+ 2
Chris is right on the mark with it. The FOR loop was created to simplify the WHILE loop structure that he posted as an example. Use a FOR loop when you've got some means of establishing the end condition. Use a WHILE loop when you're uncertain of the amount of iterations that'll take place. SYNTAX: for( <counter variable> ; <condition to break loop>; <increment counter variable)
29th Mar 2018, 7:39 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 1
Jakob and Chris already gave good explanations, but here is a code I made for someone else who asked a similar question today. I tried to use the output to explain whats happening. Keep in mind that this made the code a bit confusing for beginners. Use the original code as reference and the output of the modified code as explanation. https://code.sololearn.com/cxd0BagAnSfC/?ref=app
29th Mar 2018, 9:33 PM
Alex
Alex - avatar