In this video, we'll learn about the c++ for loop
and a few of its variations.
The for loop consists of the 4 keyword, followed by 3
expressions in parentheses.
Each of these expressions is separated by semicolon.
The semicolons are required but the expressions are all optional.
We'll see more about this later.
In its simplest form, the for loop has initialization expression
followed by a conditional expression that evaluates to a Boolean and
then an increment expression.
First, the initialization expression is executed exactly
once before any iteration occurs.
Then the condition is checked.
If it's true, the body of the loop is executed.
Then the iteration expression is executed, and we check the
condition again and repeat.
When the condition evaluates defaults, the loop is terminated,
and we continue processing the statements to follow the loop.
As you can see in this examples, the for loop can execute 1
statement or many statements by using a block statement.
Let's see a simple for loop that counts from 1 to 5.
Let's walk through this for loop 1 step at a time.
Notice that in order to count we need some sort of variable.
It's common to use the variable named I as the loop variable.
That's incremented or decremented in a loop.
In this case, we declare I to be an integer and initialize it to 0.
Now we enter the loop.
The first thing that happens is the initialization.
In this case, we assign 1 to I.
Now we check the condition since 1 is less than or equal to 5, we execute
the body of the loop which is the output statement, and we display 1.
Then we execute the increment expression, which increments I by 1.
Note that + + I and I + + mean the same thing here since the
increment happens on its own and it's not in another expression.
So now I is 2.
We check the condition again and it evaluates to true.
So we execute the body of the loop again and display 2.
Then we increment I again and keep iterating.
After we display 5 items, I will be 5.
And then we increment it to 6.
At this point, the condition fails and the loop terminates.
C++ for loops are very efficient, and in their basic form very
easy to read and modify.
Let's see another way to declare the looping variable.
We can declare and initialize the looping variable I in this case right
in the initialization statement.
This is very commonly done and has some advantages.
Here, you can see we're doing it using 2 styles.
The first uses initialization style, and the second uses assignment style.
I will be using initialization style in this course.
The looping variable I is only visible inside the for loop.
Once the loop has finished, I is no longer visible, and you'll get a
compiler error if you try to use it.
This is a great feature since you know that I is totally under your
control within the loop and won't have any strange values coming
into the loop or exiting the loop.
Let's see another example.
In this example, we're looping from 1 to 10.
The body of the loop tests to see if the remainder of I is 0.
So it's testing to see if I is an even number.
If it is, then it displays I.
So this loop displays all the even numbers between 1 and 10 inclusive.
Let's see how we can use a for loop with an array.
In this example, we're using a for loop to display
the elements of an array.
Here we've declared scores as an array of integers, and we've
initialized it to 100, 90 and 87.
Since array indexes begin at 0 and go to size -1, we must be sure
to stay within those bounds or our program could likely crash.
So we declare and initialize I to 0, and our loop
condition is I less than 3.
And we increment I by 1 at each iteration.
So we loop for i equal to 0, 1 and 2, which is exactly what we want.
The body of the loop simply displays the array element at index I.
This will display 100, 90 and 87, as we wanted.
Be very careful when you work with loops and arrays, the condition
should either be less than the size of the array or less than
or equal to the size minus 1.
Hot tip always use 1 or the other and stick to it.
Don't start flipping between them because eventually you're
going to make a mistake.
I always use less than the size of the array and I've been doing
it that way my entire career.
This helps prevent what are called off by 1 errors, which basically mean
that we went over bounds and your program could crash or corrupt data.
C++ has an operator called the comma operator.
That isn't used very often in c++.
But sometimes, you see it used in loops to initialize loop variables.
The comma operator allows you to separate expressions with a comma
and both expressions will execute.
Note that the associativity is right to left and the result of the comma
operator is the leftmost expression.
In this case, we're just using it to initialize 2 variables and then
to increment those 2 variables.
In this example, we want I to start at 1 and J to start at 5.
And we want a loop while I is less than or equal to 5.
The output statement of the body of the loop displays I * J, the product.
Then the increment also uses a comma operator to increment both I and J.
So in this case, I goes from 1 to 5 and J from 5 to 9.
And at every iteration, we display the product of I and J.
Walk through this example slowly yourself and you'll see that
it's pretty straightforward.
The syntax looks a bit odd though since there's so much going on.
The basic for loop with all 3 expressions is concise,
easy to read and modify.
In the examples I showed we used integers but you can use
doubles with for loops as well.
Also I counted up in these examples.
You of course can count down.
But since the expressions are all optional, it's possible to
have all sorts of variations.
You can even have a for loop with just the semicolons in the parentheses.
This is by definition an endless loop.
Best practice and pro tip, don't write for loops with missing
expressions and complicated expressions with comma operators.
The example I showed is simple and understandable but if
you find that you're omitting expressions, then consider
using 1 of c++ as other loops.
Great.
Let's head over to the IDE, we'll see some examples of
the for loop in live code.
I'm in the code ide and I'm in the section 9 workspace
in the for loop project.
What I want to do here is I want to write a few different for loops.
We'll write a bunch of them that behave differently.
Some will count up, some will count down.
So you get a feel for how these for loops work, and I'll write them, and
I'll comment them out along the way that way they'll be in the source
file so you can play with them later.
So let's do a simple 1 first.
Let's just say something like 4 int I, will start I at 1.
That's the initialization expression right there.
And then we want to loop while I let's say is less than or equal to 10.
And at each iteration, what we want to do is increment I by 1.
Now in this case I can say + + I or I + +, it means exactly
the same thing in this case.
And I'll simply output I.
Okay, simple as that.
Let's run this, and you can see we're going from I1 to 10.
Obviously when I hits, 11 this condition right here fails.
And I stop the loop and then I just hit this end line over
here, right before the return.
Okay, so real simple example.
Now I'll just copy and paste this so that you can see a variant of it
and I'll comment that out here now.
Suppose I want to go from I to 10 by 2.
I don't have to increment by 1., I can increment by whatever I want, so I
can hear in the increments expression I could just say, I + equals 2.
So I equals I + 2.
So we're going to do the same exact thing except when we increment,
we're going to increment by 2.
So let's run this 1, and there you go 1, 3, 5, 7, 9, exactly what I
expect because I'm starting at 1.
And then eventually, it's going to hit 11 and it'll fail.
Okay, so hopefully that makes
sense let's count down on the next one.
So let me comment that out, and let's do this now.
Let's say for int I.
And again, I is a real common variable name to use with looping i, j, k.
You'll see those all over the place in c++ code.
So let's say I want to initialize I to 10 in this case.
And I want to loop while I is greater than or equal to 0.
Let's just say greater than 0.
And in this case, I want to decrement I every time.
Okay, so again, I'm starting with I is 10.
And as long as I is greater than 0 or I is positive, I want to
execute the statement, which I'm going to write right now.
And again, I'm just going to output I.
And then I want to decrement I.
So this should count down now.
So let's try that out.
And there you go.
10, 9, 8, 7, 6, all the way down to 1.
If I write in something like this, let's say blast off,
then we expect that to execute after the loop is done.
So that works out perfectly.
There's your blast off.
And one quick thing, some compilers not all compilers but
some compilers, will give you a warning when you indent wrong.
Okay, so in this case, if I indented cout this blast off statement, over
here, that's not correct, right, because I don't have curlies.
So this for loop really only executes that one statement.
But when I see this code visually, my eyes are telling me
that those 2 statements are in the for loop, but they're not.
If I try to compile this, notice it works, but I get a warning.
The warning says warning this 4 clause does not guard.
That's not real helpful, I know.
But notice the warning message, it says misleading indentation.
That's a great warning.
A lot of compilers don't do that.
So what it's telling you is that something's not
right with the indentation.
You may think it's doing one thing but it really isn't.
So once you unindent that and indent it properly, now you'll
have a clean compile with no errors and no warnings.
That's a really nice feature of the GCC compilers.
Okay, so let me comment that piece out again.
And let's write another version of a for loop.
In this case, why don't we count from 10 to 100 x 10.
So again, for the initialization statement and
I will initialize it to 10.
Remember that only happens exactly one time right before the loop begins.
And I want to loop while I is less than or equal to 100.
And at each iteration, I want to say I + equals 10.
So I want to increment by 10 each time.
And I'm going to put in a block statement here just
because I'm going to use a few other statements in a bit.
But right now, let's just print I.
Okay, so again, we're going from 10 to 100 inclusive by 10.
So we expect this to print out 10, 20, 30, 40, all the way to 100.
Let's try that out.
And that's the result from 10 to 100 by 10 exactly what we expect.
Now suppose I only wanted to print out those numbers that are
between 10 and 100 by 10 and also divisible by 15 without a remainder.
Okay, so what we can do here is we can put an if statement here.
We can say if that specific I am looking at mod 15
is equal to 0, right.
So if that thing is divisible by 15, then I want to display it.
So at this point out of those 10, 20, 30, 40, 50 and so forth,
we really only expect 30, 60 and 90 to match this criteria.
Those are the only ones that are divisible by 0, by 15, I'm sorry.
So let's run this.
And there they are 30, 60, 90 are the only ones in that
set that are divisible by 15.
Now let's take a look at that comma operator I talked about.
The syntax for this is -- again, it's not bad.
It just gets kind of long and convoluted.
So let's try that out.
Let's say 4.
Now in this case, in the initialization statement, I want
to initialize more than 1 variable.
So I can put them all in here separated by commas,
not semicolons, commas.
So I'll say int I, and I want to initialize I to 1.
Now I put a comma in there and j to 5.
That's my initialization.
I'm setting I to 1 and j to 5.
Now comes my loop condition.
I want a loop while I is less than or equal to 5.
And now is the increment expression.
So where I say what do I want to do at each iteration.
Well, I want to increment I and I want to increment j.
So I can put the comma operator there and increment j.
Okay, so you can see the purpose of this operator within this for loop
is just to make everything concise because it makes sense here, right.
I mean I want to initialize I and j before I loop and I want to
increment them both at each iteration.
So rather than spread this logic all over the body of
this loop, you can just put it right in the header like that.
And it really conveys exactly what you want.
At this point, I can just have a simple output statement
that, let's say, we want to add I and j at each iteration.
So i want to display I.
I want to display the + symbol.
I want to display j.
I want to display the equal sign.
That's a literal.
And let's just display I + j.
And we'll end that with a new line.
So let's run that.
And you see we have 1 + 5 is 6.
Now it's -- I encourage you to walk through this example.
I mean grab your pen kind of like I'm doing right now, and
say, okay, this is I., this is j.
Right now, I've initialized them right 1 and 5.
Now I start the loop is I less than or equal to 5.
Well, I is 1.
So sure it's less than equal to 5.
I execute the body of the loop, which says display I.
Okay, 1 then the +, then the j, then the equal sign and then their sum.
Then we do the increment which means now I is 2 j is 6 and just
walk through the loop this way.
This way, you really get an understanding of what's going on.
Remember what happens.
We do the initialization one time, then we check the condition,
then we execute the body.
If it's true and then we do the increment.
So that's the order that this is all happening in.
Okay, so let me close this up.
And let's say that we wanted to use -- let's use that conditional operator
inside the loop, just like I showed you in the conditional operator video.
There's a handy way to do it here.
So suppose I want to print out the numbers 1 to 100 in a little bit of
a table format, so they look nice.
There's 10 across.
So 10 rows of 10 columns each.
How could I do that?
Well, I could do something like for sorry may indent that for int I.
We can start at 1, and we want to loop while I.
Okay, let's try that again.
Let's loop starting at int I set to 1., and I want to loop while
I is less than or equal to 100.
And in each iteration, I want to increment I.
Okay, so that's what I want to do.
I'm going to put a block statement here, so I can
write a little bit more code.
Now I want to output I.
And I don't want to put an endline here.
I just want to output the I itself.
And what I want to do is every 10th I, I want to output a new line.
Otherwise, I just want to output a space to move them across the row so.
Let's do that with the modulo operator.
I can say if I mod 10, so if it's the 10th item, equals 0.
What do I want to do here.
Well, in this case, I just simply want to say cout give me a line.
And if I is not the 10th item, I simply want to output a single space.
Okay, that's it.
So let's run this and see what we get.
You can see we're going 1 to 10, 11 to 20, 21 through 30.
And again, walk through this and you'll see exactly what's going on.
It should be pretty clear here.
I'm printing out the I, and I'm checking for every 10th item.
And if I get every 10th, I I'm going to print a new line.
Otherwise, I just put a space.
If I wanted to print this as 5 across, I can just change that
guy right there from a 10 to a 5.
And now I've got 20 rows of 5.
Okay, so that takes care of that one.
Now suppose I wanted to write this same logic using
the conditional operator.
Well, let's see.
Let's get rid of this stuff here.
And what we can say right now here with the conditional operator
is we could say, let's output that I and then let's output,
let's check the condition, right.
Same condition we had before I mod 10 equals 0.
And if that is true, we just display a new line.
We'll use the escape character, otherwise, just a space.
And if we run this, we should get exactly the same behavior
we had before, which we do.
Okay, now remember since we're outputting, we can chain output,
we can actually just get rid of all of this stuff and just make
it all in one line we can do that.
We can output the I followed by either a space or a new line.
So this can be just written as a single line.
And we get the same behavior as before.
Okay, the last example I want to go over is using a vector.
And let me comment that out.
In the slides, I showed you how to do it with an array,
how to loop through an array.
And here, I'll show you how to use a vector.
And in the next video, we'll use the range base for loop which makes
using vectors really, really simple.
But in this case, let's create a vector, and I'll just give
myself a little room here.
And I'll just call the vector nums.
And it's going to be a vector of integers.
Let's just call it nums.
And let's initialize it to, I don't know, let's say 10, 20, 30, 40 and 50.
So we've initialized it to those 5 numbers.
Now remember, we're using a vector so we have to include vector.
So I'm going to come back up to the top and pound include vector,
otherwise we'll get a compiler error.
So I'll come back down so.
There's my vector.
And let's say I want to loop through that vector and just display each
item in the vector, pretty easy.
I could say for int I and I want to initialize to 0.
Remember, vectors start at 0, just like arrays.
And I can say while I is less than nums.size, we'll use the
size method that is in the vector class okay that tells me how many
items are in the vector, and i want to increment by 1 each time.
And I just simply want to say cout nums sub-I.
Now when I run this, I expect to get 10 through 50.
We're going to get a warning, and I'll show you how to fix
that warning in a second.
And it's actually a good warning.
There you go.
10 to 50 is the output.
That's what we expected.
We're printing out all of those elements.
The warning says warning comparison between signed and
unsigned integer expressions.
Okay, what's going on here is that this numbs.size expression right
here is returning an unsigned integer, that makes sense, right,
because you can't have vectors that are negatively sized.
So that's returning an unsigned integer and you return you're
comparing it to a signed integer.
So you can just simply type unsigned here instead of signed,
and it actually makes more sense.
I've been using signed integers all along.
But a lot of times when you're looping especially when you're looping through
all the positive numbers, it makes sense to use unsigned integers here.
So I'll save that.
We'll compile and run and.
Now we've got down here, as you can see, no errors, no
warnings and a clean compile.
Okay, so that pretty much covers the basics of for loops.
I will leave all these examples in the source code so you can play with
them and change them around as you'd like, so you can learn from them.
The best way to really learn this is just to make up little examples
and print out every fifth element and see if they're divisible
by 7 or something like that.
And just really get a feel for the way that loops and walk through
these examples one step at a time that really, really is helpful.