Recitation R9
- Java: Sets & Functions
Spring 2014
CS160: Foundations in Programming
The purpose of this lab is to:
Incorporate Java with sets
Perform basic set operations
Understand usefulness of nested loops
1. Using for loops to print set elements
Create a new class in Eclipse called R9.
Write code that prints out the following sets and the number of elements in each:
x ∈ Z+ | x3 < 1000
x ∈ Z+ | x3 < 1000 and x not divisible by 3
x ∈ Z | x is even and between -13 and 9
x ∈ Z | x is even, divisible by 4 and between -7 and 23
You MUST use for loops to complete this and a variable that counts the number of elements in each set.
2. Nested for loops to print ordered pairs
Add code to your R9 program that does the following:
Prompts the user for 2 natural numbers x and y.
Checks if those numbers are in the set of natural numbers; exits if they are not.
Prints all pairs of numbers up to (x,y). Example:
Enter a natural number for x: 3
Enter a natural number for y: 2
(0,0),(0,1),(0,2)
(1,0),(1,1),(1,2)
(2,0),(2,1),(2,2)
(3,0),(3,1),(3,2)
There are 12 pairs.
You will need to use some clever placement of if checks, print and println to get the output to look exactly as shown.
You may have an extra comma at the end of each line. That's okay but think about how you might remove it.
Show your R9.java program to the TA for grading and submit to RamCT to get credit for this lab.