#what are loops, and what does this mean??

13 messages · Page 1 of 1 (latest)

stoic hare
#

in my study session, i have now been introduced to "for loop." however, i am absolutely puzzled on what this means. can somebody give me a general explanation of what they do, and what each of the 3 statements presented in the first green box mean?

#

also if anyone needs some clarification on my question, please tell me!! i'll try my best!

night scarab
#

A loop is just a block of code that runs repeatedly until a condition (think if statement) is no longer met (false).

A for loop has a 3 extra parts

for(initialization; condition; update)

  • When the loop starts the initialization runs and will not run again
  • the condition is checked before each run through the loop's block of code, if it's true the code runs, if it's false the loop stops and the code after the loop starts to run.
  • the update runs after the condition is checked and should update something that moves the code closer to a false condition (typically an increment ex i++)
stoic hare
#

so, by using a for loop and some other little blocks of code, i could have a consistently increasing number list until it hits a certain value, for which then the loop is terminated? (example of usage)

rough walrus
#

If you need an analogy, pretend you're a server at a food-stall with a queue of people waiting to order (your string in this example). Assume that no new people join the queue (assuming your string doesn't change). To serve each person, you would go one by one until the end.

To start, you begin at the first person in the queue with position 0 (int i=0, the initialisation step). You take their order and give their food so that specific person (the body of the loop). Now you add one to the position you're serving (i++) and to make sure you still have people to serve, you check if the new position you're serving is past the number of people at the beginning on the queue (i < str.length(), the condition part). This process repeats like zech said until you've served everyone

stoic hare
#

both explanations have seriously helped clear things up

#

i will certainly take this with me as i start solving problems

#

thank you both!!!

rough walrus
#

My pleasure

stoic hare
#

alright, i ran a few blocks of code from this little edu website as an experimental, and i think i figured out how it works overall

#

once again, thanks!!

rough walrus
#

Yeah for loops should be quite straightforward