For loops

1,266 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,266
On SlideShare
0
From Embeds
0
Number of Embeds
923
Actions
Shares
0
Downloads
8
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

For loops

  1. 1. CS111 Lab Iteration: for loops Instructor: Michael Gordon
  2. 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. 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. 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. 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. 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!

×