Your Turn
- Write program code to complete the provided tasks.
- Use nested loops to solve these problems.
- Run the code in the Java Playground to see if your code generates the desired result.
- Make necessary changes until you have satisfied the tasks.
Practice 1: Multiplication Table
Practice 2: Analog Clock Simulation
- Write nested loops to display every possible combination of hours (1 - 12) and minutes (0 - 59) on an analog clock, each on a separate line. Be sure to include a lead
0 for hours and minutes less than 10.
- Sample output:
01:00
01:01
...
12:59
- Try the code in the Java Playground.
Practice 3: Exam Seating Arrangement
- A hall contains 20 rows and each row has 10 seats.
- Write nested loops to print the string
"Row X, Seat Y" for each seat.
- Try the code in the Java Playground.
Practice 4: Coin Toss Simulation
- Use nested loops to generate coin tosses for 3 players. Simulate the tossing a coin for each player. Print as a string
"Player X, HEADS" or "Player X, TAILS".
- Continue to simulate the tossing of a coin until one of the players has had "HEADS" more than 5 times.
- Try the code in the Java Playground.
Practice 5: Typing Practice Until Error-Free
- A student types lines for practice. On each line attempt, there’s a 10% chance he types with no errors (Math.random() < 0.1). He continues practicing a line until he gets it error-free, then moves to the next line.
- Simulate this for 5 lines and print how many attempts it took for each.
- Try the code in the Java Playground.
Resources
Practice: Evaluate Expressions that Contain Nested Loops