## Computing Concepts with Java Essentials Laboratory Notebook Chapter 6 - Iteration

### Cay S. Horstmann Geof Pawlicki

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

• loops as repeated decisions
• types of common code that can be treated iteratively
• loop conditions and termination
• programming loops and choosing between while, for and do/while statements
• using loops to process character, word and line input
• nested loops

### 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, just like the function digits() from the preceding lab. But instead of using recursion, it uses multiple if statements.

```/* Count number of digits needed to express an integer in base 10
using multiple if statements
Note:  Compare to Ch.5 digits()
*/
public static void main(String[] args)
{  System.out.print("Input an integer between 1 and 9999: ");
int input = Console.in.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)
{  System.out.print("Input an integer between 1 and 9999: ");
int input = Console.in.readInt();
int d = 1;
int temp = input;

while (temp > 9)
{  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)
{  int millennium = 2000;

System.out.print("Please enter the current year: ");
int nyear = Console.in.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 to a do while loop

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

while( n != 0 )
{  System.out.print("Please enter a number, 0 to quit ");
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)
{  int i = 1;
int n = 1;

while(true)
{  System.out.print("Please enter a number, 0 to quit ");
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

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. Complete a function string iBeforeE(string word) that carries out this correction. That is, your function should return the corrected string (or the original string if no correction needed to be applied.)

```String iBeforeE(String word)
{  String r = "";
for (i = 0 ; i < word.length() ; i++ )
{ /*
Your work goes here
*/
}
return r;
}
```

Write a test harness to test the preceding function by feeding it many inputs.

```public static void main(String[] args)
{  boolean done = false;

while (!done)
{  /*
Your work goes here
*/
}
}
```

### 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 ".

```public static void main(String[] args)
{  for ( i = 0 ; i < 5 ; i++ )
{   System.out.print(i + " ");
}
System.out.println();
}
```
```public static void main(String[] args)
{  int decimals = 1;
while (decimals < 100000)
{  System.out.print(decimals + " ");
decimals *= 10;
}
System.out.println();
}
```
```public static void main(String[] args)
{  int i = 5;
do
{  System.out.print(i + " ");
i--;
}  while( i > 0 );
System.out.println();
}
```

### 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:

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