Unit 3 (Loops)

Repetition  

An important feature of computer programs is a loop - the ability to repeat a portion of code as many times as needed. Unlike humans, computers have no problem following the same set of instructions over and over. There are two main loops that we will learn to code repetition. The first loop falls under the definition of a definite or counted loop. It is used when we know precisely how many times we need the computer to do something. The name of this structure is the “for” loop. Here is its format:


for(initialization; continuing condition; incrementation)

Here is an example :

    for(x=1; x<=10; x++)
    {
      System.out.print((2*x) + " ");
    }

This statement says to begin the counter x at 1, continue with the loop as long as x is less than or equal to 10 and count by 1 (x++). For each value of x, the computer is instructed to display 2 times x. So we will see 2 4 6 8 ... 20 on the screen when this code executes.

Let's take a look at each part of the “for” statement:

Ininitialization

The statement "x=1" in the “for loop” initializes the counter x, or gives it a beginning value. Most loops will begin at one (or zero), but not always. It depends on the needs of the program. Initialize the counter to the value that makes sense. One note: the loop control variable (in this case, x) must be an integer.

Condition The middle part of the “for” statement is what determines the end of the loop. As long as the condition is met, the loop continues. When it is not met, the loop terminates and program flow continues on the next statement after the “for”  loop. In the example given earlier, the incrementation of x will eventually cause it to be 11. That value is not less than or equal to 10, so the loop stops.

Incrementation

The statement x++ is shorthand notation for "add 1 to x". There are two other ways to write this statement: x = x + 1 or x+=1. Counting by one is most common in for loops, but there are situations requiring counting by other numbers, or even counting backwards. Here are some examples:

    for(x=2; x<=20; x+=2) //count by two's from 2 to 20

    for(x=0; x<=100; x+=5) //count by five’s from 0 to 100

    for(x=5; x>=1; x--) //count backward by one's from 5 to 1


Counters
What's the count?   There are many instances in programs involving loops where we need to count how many times something happens or find the sum of a collection of numbers. "How," you ask? Let's look at a counter variable first.

Let's take an example. Suppose we wish to know how many integer factors a number has. Recall that a factor of a number is an integer that divides evenly into that number. For example, the number 10 has 4 factors: 1, 2, 5, and 10. Let's look at a loop that can accomplish this task. Begin by declaring a counter variable, which we will call factors. A counter variable must be declared as an int since a count must be a whole number. Also, we initialize the counter as 0 since that is where we begin, with a count of nothing.

    int factors=0, number=10, loop;

Here is the loop:

    for(loop=1; loop<=number; loop++)
    {
      if(number%loop==0) factors++;
    }

Let's examine this code. First note that the value of loop begins at 1 and ends at the number. Here this means we will check all numbers from 1 to 10 to see if they are factors of 10. When value of loop is 1, the condition number%loop==0 is true since the remainder of 12 divided by 1is 0. So the statement factors++ will enact. This statement means add one to factors. So factors is now 1. Now loop takes the value 2, which also divides into 10 evenly. So factors is now 2. The next value of loop is 3 which is NOT a factor of 10, so factors does not change. In the end, only four numbers are found to be factors of 10, so the variable factors is 4.


Summer Time  

There are other times where a sum of a group of numbers is needed. For example, suppose we want to find the sum of the numbers from 1 to 100. We need an integer summation variable for the sum because we are adding integers together. This variable must be initialized to 0 just as a counter variable is.

    int sum=0, loop;

Here is the loop:

    for(loop=1; loop<=100; loop++)
    {
      sum+=loop; //recall this means add loop to sum
    }

Another example: Suppose we wish to find the total cost of a purchase of 5 items in which decimal values are involved. First, declare the variables:

    int loop;
    double price, total = 0.0;

and now the loop...

    for(loop=1; loop<=5; loop++)
    {
      System.out.print("Enter price: ");
      price=scannerObject.nextDouble();
      total+=price; //add price to total
    }

In closing, Counters are always integers. Sums can be ints or doubles depending on what is being summed. Lastly, remember to initialize counts and sums to 0. If this is not done, you will get an error because you are trying to add to a variable that doesn't yet have a value. I guess that means that you can't add something to nothing.

Random Numbers  

The use of randomness has numerous applications from video games to computerized simulations. In Java, there are a few ways to generate random integers. We will use the random method from Java's Math class.

The Math class random method is used as follows :

    double x = Math.random(); //random decimal from 0-1 including 0 but not 1

OR Generate a random number and display it without storing the value:

    System.out.println( Math.random() );

To generate a random integer from 0 to n-1:

    int y = (int) (n * Math.random());

OR more usefully, we generate a random integer from 1 to n:

    int y = (int) (n * Math.random()) + 1;

In general, to generate a random integer between a and b:

    int y = (int) ((b-a+1) * Math.random()) + 1;


In closing, The Math class random method generates decimal values. To get the necessary integer for a program, use the appropriate formula as follows:


      1.  0 to n-1 : (int) (n * Math.random())
      2. 1 to n   : (int) (n * Math.random()) + 1
      3. a to b   : (int) ((b-a+1) * Math.random()) + 1

Conditional Repetition  

Many times we need repetition of unknown number in Java. A “for” loop is great for known repetition, but what if you don't know how many times you need to do something? That's where the while loop comes in.

Here is the format:

    while(condition)
    {
      list of statments...
    }

You will probably note that a while loop looks a lot like an if statement. In fact a while loop is an “if” statement that can repeat. In other words, it keeps asking the question until it gets an answer of false. So as long as the condition is true, it will continue to do the list of statements.

Example:

Suppose we want to enter an unknown number of positive integers and then find the average of those integers. We can't use a “for” loop because we don't know how many numbers there are. We can use a while loop though, and have a negative value represent the signal to stop entering numbers. Here is how we will do it:

int number=0, sum=0, count=0;
while(number>=0)
{
    System.out.println("Enter a positive integer: ");
    number = scannerObject.nextInt();
    if(number>=0){count++;sum+=number;}

}
      double average = sum / (1.0 *count);

In this example, once a negative number is entered, the condition number>=0 becomes false and the loop is terminated. The computer always checks the condition first before entering the loop. If the condition is true, the loop is entered. If not, it skips to the next line of code that follows the while loop.

While in Place of For  

If there were no “for” loop in Java, we could mimic its function with a well-crafted “while” loop. Take note of the following example:

    int count=1;
    while(count<=10)
    {
      System.out.println(count);
      count++;
    }

This while loop is equivalent to the following “for” loop:

    for(count=1; count<=10; count++)System.out.println(count);

Infinite Loops  

It is possible to write a while loop that may not stop - meaning its condition never reaches a false state. Take note of the following example:

    int count=1;
    while(count!=10)
    {
      System.out.println(count);
      count+=2;
    }

The value of count starts at 1, then becomes 3, 5, 7, etc.... Thus count is always an odd number, making it impossible to equal 10. So the condition count!=10will always be true. An always true condition makes this loop go on forever, causing a crash as the computer can only take so much of this! We call this phenomenon an infinite loop.

Remember: The while loop is useful in situations where repetition is needed, but the number of repetitions is unknown. This usually means that repetition should continue until a given condition is false. Lastly, be careful to ensure the condition can be false or you run the risk of an infinite loop, causing the program to crash


Nested Loops:

A nested loop is a loop placed inside another loop.

 

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= 10; j++) {

System.out.print("*");

}

System.out.println(); // to end the line

}

• Output:

**********

**********

**********

**********

**********

• The outer loop repeats 5 times; the inner one 10 times.

– "sets and reps" exercise analogy

Example:    What is the output of the following nested for loops?

 

for (int i = 1; i <= 5; i++) {

for (int j = 1; j <= i; j++) {

System.out.print("*");

}

System.out.println();

}

 

Output:

*

**

***

****

*****


Example:

 

for (int line = 1; line <= 5; line++) {

for (int j = 1; j <= (-1 * line + 5); j++) {

System.out.print(".");

}

System.out.println(line);

}

• Output:

....1

...2

..3

.4

Break and Return:

        break in a loop instructs the program to immediately quit the current iteration and go to the first statement following the loop.

        return in a loop instructs the program to immediately quit the current method and return to the calling method.

        A break or return must be inside an if or an else, otherwise the code after it in the body of the loop will be unreachable.

Break Example:

int d = n - 1;

  while (d  > 0)

  {

      if (n % d == 0)

          break;

      d--;

  }

  if ( d > 0 )   // if found a divisor

 

 

Return Example:

public int search(String[ ] list, String word)

{

  for (int k = 0;  k < list.length;  k++)

  {

      if (list[k].equals (word)

          return k;

  }

  return -1;

}

 

** You can also use the statement “return;” to immediately quit a void method.

Caution about Break Statement:

for (int r = 0;  r < m.length;  r++)

   {

    for (int c = 0;  c < m[0].length;  c++)

    {

        if (m [ r ][ c ] == 'X' )

            break;

    }

   }

 

**This “break” breaks out of the inner loop but continues with the outer loop.