IT - for Loops (Lesson)
for Loops
Introduction
When examining iteration, we will encounter 2 different types of loops: definite and indefinite. while loops are indefinite loops since we cannot determine the number of iterations by looking at the heading. for loops are definite loops because the number of iterations through the loop is predetermined. The number of iterations can be determined from the heading.
for Loops
The structure of a "for loop":
This loop will iterate 6 times.
In the for loop heading, the i acts as a counter. The initialization statement is only executed once before the boolean expression is evaluated. It will start at zero and increment by 1 after each iteration of the loop. The loop will only iterate when i is less than 6. We can see right away that this loop will iterate 6 times.
Try writing a loop that will print the numbers 1 through 20. Answer below:
A for Loop can also be written as an equivalent while loop. How would you write the previous for loop into a while loop?
Notice that the counter, i, has been initialized outside of the loop and incremented inside of the loop. The boolean condition is part of the while loop heading.
When reading code that contains a loop it can be traced by hand to see what is happening with each iteration.
Loop Tracing Video
Check out the following video to see how to trace code by hand.
More Iteration Videos
Click below to watch the two videos below that are free response question videos.
Another FRQ Video
Watch out for “off by one” errors. This is when the iteration statement loops one time too many or one time too few. We will see this when we look at for loop applied in free response problems or programs.
Click on "Runestone Academy" below to open the required reading that is listed.
Runestone Academy: AP CSA – Java Review Links to an external site.:
READ: 7.3 – For Loops
Click on Introduction to Computer Science using Java below to open the required reading that is listed.
Introduction to Computer Science Using Java Links to an external site.:
READ: Chapter 24: The for Statement
Chapter 25: More about the for Statement
Complete the quizzes for practice.
5 Steps to a 5:
Skim the Practice Exams.
for Loops Challenge
Create a loop which will take a String and reverse the order of the characters causing it to print backwards. For example, using the name, Stan Lee, the output would be eeL natS.
See answer below. Your answer may vary. Test it in Dr. Java!
Answer:
Go to the PracticeIt website
Links to an external site..
- Log into account.
- Click on Start Practicing!
- Go to the most recent edition.
- Click on Chapter 2: Primitive Data and Definite Loops. Complete Exercises 2.2 & 2.3
- Click on Chapter 3: Parameters and Objects. Complete Self-Checks 3.4, 3.5 and Exercise 3.19.
- Click on Chapter 5: Problem Logic and Indefinite Loops. Complete Exercise 5.4.
IMAGES CREATED BY GAVS