Computing Concepts with Java Essentials
Laboratory Notebook
Chapter 6 - Iteration

Your name:
Your email address:
Your student ID number:

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.


Lab Objectives

To gain experience with


P1. Simple Loops

Frequently, a decision needs to be made whether or not to do something again. Here is a program that computes the number of digits needed to represent a number in base 10.

/* Count number of digits needed to express an integer in base 10
   using multiple if statements
*/
public static void main(String[] args)
{  ConsoleReader console = new ConsoleReader(System.in);
   System.out.println("Input an integer between 1 and 9999:");
   int input = console.readInt();
   int temp = input;
   int d = 1;

   if (input < 1 || input > 9999) return;

   if (temp > 9)
   {  temp = temp / 10;
      d++;
   }

   if (temp > 9)
   {  temp = temp / 10;
      d++;
   }

   if (temp > 9)
   {  temp = temp / 10;
      d++;
   }

   if (temp > 9)
   {  temp = temp / 10;
      d++;
   }

   System.out.println(input + " can be expressed in " + d + " digits");
}

But having to write

   if (temp > 9)
   {   temp = temp / 10;
       d++;
   }

four times, even using copy/paste, is clearly repetitive! It also only works for input <= 9999. One would like to have a way of testing that the input is still greater than 1, and executing the succeeding control block if it is. Replacing if with while does it.

/* Count number of digits needed to express an integer in base 10
   using while loop
*/
public static void main(String[] args)
{  ConsoleReader console = new ConsoleReader(System.in);
   System.out.println("Input an integer between 1 and 9999:");
   int input = console.readInt();
   int d = 1;
   int temp = input;

   while (temp >= 10)
   {  temp = temp / 10;
      d++;
   }

   System.out.println(input + " can be expressed in " + d + " digits");
}

The fractions 1/2, 1/4, 1/8, ... get closer and closer to 0. Change the previous program to count the number of divisions by two needed to be within 0.0001 of zero.

P2. Loop Termination

Which values of nyear cause the following loops to terminate?

/* Count number of year between a user-input year and the
   year 2000.
*/
public static void main(String[] args)
{  ConsoleReader console = new ConsoleReader(System.in);
   int millennium = 3000;
   System.out.println("Please enter the current year:");
   int nyear = console.readInt();
   while (nyear != millennium)
   {  nyear++;
   }

   System.out.println(" Another " + (millenium - nyear) + "years to the millenium.");
}

Re-write the preceding program so that the while loop will terminate for any integer input.


P3. for Loops

A variable that counts the iterations of a loop is called a loop index. In the preceeding examples nyear serves as an index, counting the number of years to the millenium. This type of loop is frequently written using the for idiom.

for (loop_index = start_value; condition; index_increment)

Write a program controlled by two for loops which produces the following listing of inclusive dates, from the 5th Century B.C. through the 5th Century A.D.

Century 5 BC  400-499
Century 4 BC  300-399
Century 3 BC  200-299
Century 2 BC  100-199
Century 1 BC  1-99
Century 1 AD  1-99
Century 2 AD  100-199
Century 3 AD  200-299
Century 4 AD  300-399
Century 5 AD  400-499

Write the same program with a single loop for (i = -5 ; i <= 5 ; i++) and an if in the body of the loop.


R1. Other Loops

One loop type might be better suited to a purpose than another. The following usages are idiomatic.

for Known number of iterations
while Unknown number of iterations
do while At least one iteration


Convert the following while loop to a do while loop

/* Program to compute a running sum of user-input integers
*/
public static void main(String[] args)
{  ConsoleReader console = new ConsoleReader(System.in);
   int sum = 0;
   int n = 1;

   while (n != 0)
   {  System.out.println("Please enter a number, 0 to quit:");
      n = console.readInt();
      if (n != 0)
      {  sum += n;
         System.out.println("Sum =  " + sum);
      }
   }
}

Is this an improvement? Why?

Convert the inner while loop to a for loop

/* Program to compute the first integral power to which 2 can be
   raised that is greater than that multiple of a user-input integer.
*/

public static void main(String[] args)
{  ConsoleReader console = new ConsoleReader(System.in);
   int i = 1;
   int n = 1;

   while (true)
   {  System.out.println("Please enter a number, 0 to quit:");
      n = console.readInt();
      if (n == 0) return;
      i = 1;
      while (n * n > Math.pow(2,i))
      {   i++;
      }
      System.out.println("2 raised to " + i
         + " is the first power of two greater than " + n + " squared");
   }
}

Is this an improvement? Why?

Convert to a while loop:

public static void main(String[] args)
{  int i;

   for (i = 1; i <= 10; i++)
   {  System.out.println(i + " squared equals " + i * i);
   }
}

Is this an improvement? Why or why not?


P4. Iterating through a string

You can access the individual characters in a string by the charAt method of the String class. The charAt method returns a character of type char. Note that char constants are enclosed in single quotes such as 'e'.

Many word-processors can check spelling. One of the corrections applied is to swap 'e' for 'i' if 'i' occurs immediately before 'e' and immediately after 'c'. For example, concieve is corrected to conceive. Write a program that carries out this correction. That is, your program should read a string and print the corrected string (or the original string if no correction needed to be applied.)

You can access through the individual words of a string by using a StringTokenizer.

StringTokenizer tokenizer = new StringTokenizer(aString);
while (tokenizer.hasMoreTokens())
{  String word = tokenizer.nextToken();
   do something with word
}

Write a program that reads a line of input from the user and then prints out all words in the input line that start with an uppercase letter. For example, if the input line is My mother lives in Maine and drives a Mercedes, then your program prints

My
Maine
Mercedes

R2. Tracing Loops

1) What is the output of each of the following loops?

2) In each example, leave the loop as it is and change only the expression inside System.out.print so that the program will display "1 2 3 4 5 ".

for ( i = 0 ; i < 5 ; i++ )
{   System.out.print(i + " ");
}
int decimals = 1;
while (decimals < 100000)
{  System.out.print(decimals + " ");
   decimals *= 10;
}
int i = 5;
do
{  System.out.print(i + " ");
   i--;
}  while( i > 0 );

P5. Nested Loops

Write a program to draw a top view of 24 beer cans, that is 24 circles, arranged in a 4 x 6 grid like this:

4 by 6 Beercans


Don't forget to send your answers when you're finished.