2. for loop structure
Think of a for loop as a special kind of
while loop with initialization, comparison,
and incrementation built in.
for (int i = 0; i<n; i++){
instructions…
}
3. Simplest for loops
The previous slide shows one of the most
common types of for loops.
Initialize an integer (i) to zero.
Increment by one (i++)
As long as i<n (i is less than some number n)
To count backwards from n, you could do:
for (int i = n; i<0; i--)
In addition to incrementing you can do:
for (int i = n; i<0; i=i+5) etc.
4. When to use for loops
Use while loops when you don’t know the
number of iterations (such as if the
condition to check depends on the user).
Use for loops if you know how many times
you need to loop
5. Nested for loops
You can “nest” one for loop (or more)
inside of another for loop.
for (int i = 1; i<=2; i++){
for (int j = 1; j<=2; j++){
instructions…
}
}
6. Nested for loops
The “i” loop runs twice and the “j” loop
runs twice each time the “i“ loop runs.
for (int i = 1; i<=2; i++){
for (int j = 1; j<=2; j++){
instructions…
}
}
Make sure to use different variables!