Lab 10
Lab 10
In this lab you will print a table using a single loop. In addition, nested loops are an important tool in programming. Some
tables can be printed using a nested loop but, there are many other uses. Since you can't write a nested loop unless
understand how it is executed, you will practice doing a walk through of some nested loops.
Read : Chapter
copy the files Primes.java and NestedLoops.java
This is an individual lab. You may ask the lab tutor for help, and you may consult with your neighbor if you are
having difficulties.
In this lab, you will modify the and add to the two copied programs.
When done with each program, do a final run of each program and place a copy of the printed output in each file.
When you have completed the lab, hand in your printouts to the lab tutor.
PAGE 10.1
10.1 FINDING PRIME NUMBERS
The positive factors, or divisors, of 2 are 1 and 2 .
The positive factors, or divisors, of 6 are 1, 2, 3, and 6.
The positive factors, or divisors, of 9 are 1, 3 and 9.
D e f i n t i o n : A prime number is a positive integer that has two distinct factors, 1 and itself.
The number one is not a prime number since it does not have two distinct factors.
The number two is the smallest prime number and the only even number that is a prime.
-1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Therefore, to determine if a positive integer number is a prime number, check if any of the integers between 2
and (number – 1) are divisors, or factors, of number.
The following algorithm, described using pseudocode, determines if int number is a prime number.
PAGE 10.2
J A V A L A B M A N U A L
if(number < 2)
isPrime = false;
else if(number > 2)
{
//look for a divisor of number
//if a divisor is found, set isPrime to false
}
return isPrime;
}
Compile and run the program. For which of the numbers tested in the main method, does isPrime return true?
__________________________________________________________________________________________
__________________________________________________________________________________________
PAGE 10.3
S t e p 3 : Add the loop that looks for a divisor of number. When a divisor is found, isPrime is set to false and, for
efficiency, the loop should stop. When a break statement is executed inside of a loop, the loop terminates and the next
statement following the loop is executed.
private static boolean isPrime(int number)
{
boolean isPrime = true;
if(number < 2)
isPrime = false;
else if(number > 2)
{
for(int divisor = 2; divisor < number; divisor++)
{
if(number % divisor == 0)
{
isPrime = false;
break;
}
}
}
return isPrime; //when the loop ends, isPrime is returned
}
Compile and run the program. For which of the numbers tested in the main method, does isPrime return true?
__________________________________________________________________________________________
__________________________________________________________________________________________
We now have a working method. However, that does not mean that we are done. You should always re-read your code to
see if improvements can be made to its appearance, its readability, its logic, or its efficiency. What improvements can be
made to the isPrime method?
Since two is the only even prime number, we could make a special case for even numbers, so that only odd
numbers are checked by the loop.
If the loop no longer needs to check for divisibility by two, it no longer needs to check for divisibility by any other
even number. That is, we only need to check for divisibility by the odd numbers 3, 5, 7, ...
The number 53 is a prime number. How many possible divisors must be checked. Do we need to check all of the
odd numbers between 3 and 52, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 24, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47,
49, and 51? The answer is no, but where can we stop?
PAGE 10.4
J A V A L A B M A N U A L
if(number < 2)
isPrime = false;
else if(number > 2)
{
if(number % 2 == 0) //even numbers are not prime
isPrime = false;
else
{
double sqrt = Math.sqrt(number); //evaluate once
Compile and run the program. For which of the numbers tested in the main method, does isPrime return true?
__________________________________________________________________________________________
__________________________________________________________________________________________
S t e p 5 : Note that the only values stored in number that allow the code to execute are odd.
for(int divisor = 3; isPrime && divisor <= sqrt; divisor += 2)
{
if(number % divisor == 0)
isPrime = false;
}
Use a table of values to do a walk-through of the loop.
PAGE 10.5
__________________________________________________________________________________________
__________________________________________________________________________________________
What condition makes the loop end when number = 53?
__________________________________________________________________________________________
__________________________________________________________________________________________
2 3 5 7 11 13
17 19 23 29 31 37
41 43 47 53 59 61
67 71 73 79 83 89
97 101 103 107 109 113
127 131 137 139 149
PAGE 10.6
J A V A L A B M A N U A L
__________________________________________________________________________________________
S t e p 7 : Obviously, we need to print newline characters to force new rows. In many charts, every calculated value is
printed, and the placement of the newline character is determined by the loop counter, num. However, in the prime chart,
not all values of num are printed. Therefore, another criteria is needed to determine when the newline character should be
printed.
If six columns of numbers are desired, a newline character will be printed after the sixth, twelfth, eighteen, twenty-fourth,
etc. primes are printed. If we introduce a separate counter that is incremented every time a prime number is printed, then a
newline character is printed when the counter is 6, 12, 18, 24, . . . These values all have something in common – they are
divisible by 6.
Modify the printPrimeChart method to incorporate the needed changes.
public static void printPrimeChart(int min, int max)
{
int counter = 0; // determines when a newline character is printed.
System.out.println(" Primes Between " + min + " and " + max + "\n");
Compile and run the program. Does the chart print as planned? Explain any problems in the appearance.
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
S t e p 8 : Before we handle the alignment problem in our chart, change the code to print seven columns of prime
numbers instead of six. Add another call to printPrimeChart in main to print prime numbers between 999,000
and 1,000,000.
Compile and run the program. What is the largest prime number less than 1,000,000? How many prime numbers
are between 999,000 and 1,000,000?
__________________________________________________________________________________________
__________________________________________________________________________________________
__________________________________________________________________________________________
PAGE 10.7
Columns can be aligned to the left or right easily using some of the new features added to Java 1.5.
These options have much more versatility that we need for our prime chart or than we care to discuss here.
If you would like to read the online documentation, I suggest that you begin with the Formatter class.
For now, we will use the printf method.
S t e p 9 : Now, call the printf method from the printPrimeChart method, by replacing the statement
System.out.print(num + " ");
with the statement
System.out.printf("%10d", num);
that right aligns each integer value ("%d") in a field-width of ten.
Compile and run the program.
Record any alignment problems.
__________________________________________________________________________________________
__________________________________________________________________________________________
S t e p 1 0 : To left align each number in field-width of ten, place a negative sign in before the 10 in the statement
System.out.printf("%-10d", num);
PAGE 10.8
J A V A L A B M A N U A L
The loop to print a row, prints one symbol at a time. After the row is printed, a newline character is printed.
for(int c = 1; c <= columns; c++)
When columns are 5, the loop is executed
{
5 times. Each time through the loop
System.out.print(symbol);
symbol is printed.
}
System.out.println(); When the loop ends, a newline is printed.
PAGE 10.9
void printRectangle(int rows, int columns, char symbol)
{
for(int r = 1; r <= rows; r++)
{
for(int c = 1; c <= columns; c++)
{
System.out.print(symbol);
}
System.out.println();
}
}
Let's do a walk through of this nested loop for the method call.
printRectangle(3, 5, '?');
Notice, that when r is 1, the inner loop is executed five times. After the newline is printed, r is incremented to 2 , and the
inner loop is again executed 5 times. etc.
r <= rows c <= columns
r c prints
r <= 3 c <= 5
1 true 1 true ?
2 true ?
3 true ?
4 true ?
5 true ?
6 false \n
2 true 1 true ?
Prints:
2 true ?
?????
3 true ? ?????
4 true ? ?????
5 true ?
6 false \n
3 true 1 true ?
2 true ?
3 true ?
4 true ?
5 true ?
6 false \n
4 false
S t e p 1 : Open the file NestedLoops.java , which calls the method
public void printRectangle(int rows, int columns, int symbol)
from the run method. Compile and run the program to verify that it works as discussed.
PAGE 10.10
J A V A L A B M A N U A L
row spaces stars newline the outer loop will be controlled by the row #
----* 1 4 1 \n for(row = 1; row <= 5; row++)
---** 2 3 2 \n {
--*** 3 2 3 \n a loop to print spaces;
-**** 4 1 4 \n a loop to print stars;
***** 5 0 5 \n print a \n;
}
For the first nested loop that prints the spaces, we need a relationship between the number of the row and the number of
spaces that are printed.
Notice that row + spaces = 5 . Therefore, spaces = 5 – row.
For the second nested loop that prints the stars, we need a relationship between the number of the row and the number of
stars that are printed.
Notice that stars is equal to row.
The completed loop
for(int row = 1; row <= 5; row++)
{
for(int spaces = 1; spaces <= 5 - row; spaces++)
System.out.print(‘ ’);
for(int stars = 1; stars <= row; stars++)
System.out.print(‘*’);
System.out.println();
}
Add a method
public void printTriangle1(int rows, char symbol)
that generalizes the above loop to handle any number of rows. Add several calls to the method from the run method in
NestedLoops.java to test your method.
Compile and run the revised program.
S t e p 3 : Add two methods
public void printTriangle2(int rows, char symbol)
public void printTriangle3(int rows, char symbol)
each of which prints a triangle like the two below which have rows equal to 5. Follow a thought process like the thought
process demonstrated above. Each rectangle lines up with the left side of the monitor.
printTriangle2 (no spaces need to be printed) printTriangle3 (print only leading spaces)
***** *
**** ***
*** *****
** *******
* *********
PAGE 10.11
10.5 PRACTICE WALK-THROUGHS OF NESTED LOOPS
The following two exercises are typical quiz/test questions.
Follow the code on paper first. Then, in the run method of the program NestedLoops.java , uncomment the call to the
appropriate method. Run the program and check your answers.
S t e p 3 : First, predict what is printed by this code. Then check your answer by uncommenting the call to quiz1() in
the run method. Compile and run the program.
public void quiz1()
j j<5 k k<5
{
int j, k=0;
Prints:
S t e p 4 : First, predict what is printed by this code. Then check your answer by uncommenting the call to quiz2() in
the run method. Compile and run the program.
{
int j, k=0;
Prints:
PAGE 10.12