CS173: Intro to Computer Science - Iteration with the for Loop
Activity Goals
The goals of this activity are:- To be able to explain the uses of the
for
loop structure - To be able to apply boolean expressions to iterative structures via the
for
loop
Supplemental Reading
Feel free to visit these resources for supplemental background reading material.The Activity
Directions
Consider the activity models and answer the questions provided. First reflect on these questions on your own briefly, before discussing and comparing your thoughts with your group. Appoint one member of your group to discuss your findings with the class, and the rest of the group should help that member prepare their response. Answer each question individually from the activity on the Class Activity Questions discussion board. After class, think about the questions in the reflective prompt and respond to those individually in your notebook. Report out on areas of disagreement or items for which you and your group identified alternative approaches. Write down and report out questions you encountered along the way for group discussion.Model 1: The for
Loop
Conditionals can be used to repeatedly execute code. There are three varieties of these “loops:” the for loop (which is useful when counting the number of iterations that are needed), the while loop (which is useful for executing until something is true), and the do loop (similar to the while loop, but it executes at least once and checks whether it should stop at the end of the loop, rather than at the beginning).
Questions
- The code prints the numbers from 0 through 9. Why doesn’t it also print the value 10?
- What could you do to change this to print the values 0 through 10?
- What could you do to print the values 1 through 10?
- What might you change in the code to print only the even values between 0 and 9, changing only the line beginning with for?
Model 2: Nested Loops
Questions
- How many times does the inner loop print statement execute?
- How many times does the outer loop print statement execute?
- How many times does the first print statement execute, and why?
Model 3: Finding the Error
Questions
- What does this program do if you execute it?
- Why does this program fail to do what you would expect?
Model 4: Flipping a Coin
Questions
- How many times would you expect to land on heads?
- What would you change to flip the coin 100 times? How many heads would you expect then?
- What would be the effect of changing the constant in the program from 0.5 to 0.3?