Loops
EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG
Learning Outcomes
Understand about Loops :
- Motivation: Repetition of similar actions
- Two common loops: for and while
- Primitive vs. Compound Statements
- Nesting loops within if statements
- Nesting if statements within loops
- Common Errors and Pitfalls
2 of 77
Motivation of Loops
- We may want to repeat the similar action(s) for a (bounded)
number of times. e.g., Print the “Hello World” message for 100 times e.g., To find out the maximum value in a list of numbers
- We may want to repeat the similar action(s) under certain
circumstances. e.g., Keep letting users enter new input values for calculating the BMI until they enter “quit”
- Loops allow us to repeat similar actions either
- for a specified number of times; or
- while a specified condition holds true.
3 of 77
The for Loop (1)
for (int i = 0; i < 100; i ++) { System.out.println("Welcome to Java!"); }
4 of 77