In this lecture I want to go over my favorite loop before loop.
So we saw in the while loop lecture this example where we count from one to some max number and you
set the max to 10.
Well there's a different loop called the for loop that is very good at counting.
So let's try to do for loop example just a just like the one above.
So you say it equals to 1 eyes less than or equal to Max
and plus plus C.
Current generation is
in.
And if we run this see 1 to 10.
So we print 1 to 10 and that's the while loop.
So this first 9:59 is just the while loop and the next 9:59 is our FOR loop.
So it does the exact same thing as the wild.
So let's unpack this syntax a little bit and trying to understand what's going on.
So we have the four and then we have the parentheses just like normal.
And next we have this thing called in die equals to 1 inside the for loop.
So this is actually where we define our iteration very.
So the iteration variables defined in the four look and this this is defined only once.
It only get created one one time at the very start of the for loop and we can just set it to whatever
we want.
In this case it's 1 and we have a semi-colon.
This is really to delimit the different sections of the form.
So the first section is the creation of our iteration variable just like we did up here.
But actually inside the loop itself and next is just the condition just like we had with the same condition
exact same.
So it's always creation of our iteration variable.
Then we check the the condition to see if it's true or not.
And then skip this for now.
And we're going to go to here.
So we just do all our statements just like normal just like we had in our while loop.
And then at the end at the very end of all the statements in the for loop then we will go and do this
plus plus just like we have here.
So these are really just equivalent.
So we do all the statements and then at the end we do plus plus and then we'll check again for the next
iteration to see if the condition is true or false.
So really this for loop and this while loop are equivalent and you can see that in the output.
So this just another way a nice convenient way remember that programmers really like convenience.
So this is a very convenient way of counting and I know the syntax is a bit strange at first but I think
you'll start learning to love having this for loop instead of doing doing it this way every time.
So one thing to note though is we could use this variable outside of of the Y.
So in fact we declared or defined it really outside of the Waialua but this variable is actually a different
arbitrary variable and the variable only for the for loop.
So we can't use this variable outside of the for loop at all.
So that's just one thing to keep in mind.
So in the next lecture I want to go over some things that can modify the flow of our loops.