Download presentation
Presentation is loading. Please wait.
1
Week 5 - Friday CS 121
2
Last time What did we talk about last time? Repetition while loops
3
Questions?
4
Project 2
5
Exam 1 Post Mortem
6
while Loop Examples
7
while( condition ) { statement1; statement2; … statementn; }
Anatomy of a while loop while( condition ) { statement1; statement2; … statementn; } A whole bunch of statements
8
Guessing game Let’s say that you wanted to write a program to guess a number that a person had come up with The number is between 1 and 100 Every time the computer guesses a number, the person enters: H if the number is too high L if the number is too low F if the number was found
9
Guessing game algorithm
Start with the minimum and maximum of the range Find the midpoint Ask the user if the midpoint is correct If the answer is too high, go to Step 1 using the minimum and the midpoint - 1 as the new range If the answer is too low, go to Step 1 using the midpoint + 1 and the maximum as the new range If the midpoint is correct, you’re done!
10
Nested loops Just as with if-statements, it’s possible to nest loops
A repetitive task can be done inside of another repetitive task Be careful! You can make the computer do a lot of work
11
Triangular numbers Triangular numbers are 1, 3, 6, 10, …
1 = 1 3 = 1 + 2 6 = 10 = Let’s write a program that expresses the nth triangular number by printing 1 on the first line, 1 and 2 on the second line, 1, 2, and 3 on the third line, and so on
12
Lab 5
13
Upcoming
14
Next time… for loops More loop examples
15
Reminders Keep reading Chapter 5 Keep working on Project 2
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.