CS 111A Lecture Notes - Loops - Chapter 4
Loops
- loop - a way of repeating a block of code while a specified condition is true. Use a loop when
you want to repeat a task.
- "while" loops have two main formats:
- Notice the placement of semi-colons above.
- Beware of infinite loops!
- Notice that "do" cannot stand alone. "do" is only used at the beginning of a do...while loop.
- Rules regarding use of curly braces "{" and "}" - If you want more than one line of code in the
result/body of an if-statement, else-statement, or loop, then that result/body code must be enclosed by
curly braces. They define a block of code with its own scope (We'll learn more about this later.)
Examples of while loops
Advanced Loop Control: break and continue
- break - a Java statement that is used only inside a loop or switch structure, to exit that
structure and move on with what follows it.
- continue - a Java statement that is used only inside a loop, to skip the rest of the loop
body, and test the loop condition again, starting a new iteration if the condition is true.
- NestedControlStructure.java inputs and shows student
info with if-else-if inside loop
- NestedAlt.java: Alternate version of above using "break"
- In-class exercise: Write a program that inputs numbers from the user, using -1 to terminate the
input. The program should then display the average of all the numbers, and how many were entered.
- AverageNumbers.java: Solution to above in-class
exercise to average and count numbers input by user
For-loops
Random Number Generation
- To generate a random number, use the Math.random() function. It returns a number between 0
and 1 (greater than or equal to 0, but less than 1). You can multiply that result times any number to get
a random number between 0 and your multiplier. For example, the following line will make id store a
random
integer between 0 and max-1 (inclusive):
int id = (int)(max * Math.random());
- In-class exercise: Write a program to generate random integers between 5 and 10 (inclusive),
showing them on the screen, and stopping when the same number is generated twice in a row. At the end,
output the largest number that was generated.
- RandomExercise.java: solution to above in-class exercise.
Nested Loops
Return to the main CS 111A page