REPETITION  CONTROL  STRUCTURES -  LOOPS (do-while, for)

TOPICS


·       The do-while Statement: Definition, Syntax, Terminology, Examples

·       do-while vs. while Comparison

·       The for Statement: Definition, Syntax, Terminology, Examples

·       The break and continue Statements.

·       Choosing the most appropriate looping statement for a given problem.

·       Additional Java Programming Concepts: Generating Random Numbers

·       Exercises and Sample Programs


OUTLINE



1. The do-while statement

 do{
    <statement>
    <statement>
    ... //loop body
    ...
 } while(Expression);

Description: Description: Description: C:\Courses-NOW\Webpage\236\LectureNotes\L7-DoWhile.JPG


       ...
   int counter = 1;
   do {
       System.out.print(counter + "  ");
       counter++;
   } while(counter <= 10);
   System.out.println();
 

//Some HR application: employee info
//Input validation with do-while
...
Scanner input = new Scanner(System.in);
char gender;
int age;
...
do {
    System.out.print("Enter age: ");
    age = input.nextInt();
    if(age <= 16)
        System.out.print("\nInvalid! ");
} while(age <= 0);

do {
    System.out.print("Enter gender(M/F): ");
    gender = input.next().charAt(0); ;
    if(gender != 'M' && gender != 'F')
        System.out.print("\nInvalid, should be M or F. ");
} while(gender != 'M' && gender != 'F');
...

Note: A do-while statement does not require priming read, so the input steps don't appear twice (once before the loop, once inside the do-while body, at the end of the loop), but it does test the input value twice.

·  do-while loop  vs. while loop

 

DO-WHILE (post-test loop)

 WHILE (pre-test loop)

POST-TEST loop (exit-condition)

PRE-TEST loop (entry-condition)

The looping condition is tested AFTER executing the loop body.

The looping condition is tested BEFORE executing the loop body.

Loop body is always executed at least once.

Loop body may not be executed at all.

 

while loop:

do-while loop:

int age;
Scanner input = new Scanner(System.in); 

System.out.print("Enter age: ");
age = input.nextInt();
while(age <= 0){
   System.out.println("Must be positive. ");
   System.out.print(" Enter age: ");
   age = input.nextInt();
}

int age;
Scanner input = new Scanner(System.in); 

do{
   System.out.print("Enter age: ");
   age = input.nextInt();
   if(age <= 0)
       System.out.println("Must be positive! ");
} while(age <= 0);
 

 

while loop:

do-while loop:

// ...
Scanner input = new Scanner(System.in); 
int sum = 0, n;
int count = 1;
n = input.nextInt();
while (count <= n){
    sum = sum + count;
    count++;
}
System.out.println("sum = " + sum);

// ...
Scanner input = new Scanner(System.in); 
int sum = 0, n;
int count = 1;
n = input.nextInt();
do{
    sum = sum + count;
    count++;
} while(count <=n);
System.out.println("sum = " + sum);

Note: The output may not be the same for all values of n. If n > 0, both versions have the same output. But, if n <= 0, the 2 loops give different outputs. With while,sum = 0 (loop body never entered). With do-while,sum = 1 (the body executes once and the condition is tested after).

2. The for statement

 
for(initialization;test expression; update){
    0 or more statements to repeat
}

Equivalent to:
 

initialization;
while(test expression){
    0 or more statements to repeat
    update;
}

 
int number;
for(number = 1; number <= 10; number++){
    System.out.println("The number is: " + number);
}
System.out.println("Done");

Note: When the loop control condition is evaluated and has value false, the loop is said to be satisfied and control passes to the statement following the for statement.
 

int number;
for(number = 10; number >= 1; number--){
    System.out.println("The number is: " + number);
}
System.out.println("Done");

 
int sum = 0;
for(int n = 1; n <= 10; n++){
   sum = sum + n;
}
System.out.println("Sum is: " + sum);

Equivalent to:

int sum = 0;
int n = 1;
while(n <= 10){
   sum = sum + n;
   n++;
}
System.out.println("Sum is: " + sum);

for(int i = 1; i <= 10; i++)
    System.out.println("Something ");

Note: iis a local variable whose scope will extend only to the end of the for statement. Being a local variable,iis inaccessible outside the for statement.
 


 

int i, j;
for(i = 1; i <= 5; i++){
    for(j = 1; j <= i; j++)
        System.out.println(j);
}


 

int x, y;
for (x = 0, y = 0; x + y < 1000; x++, y++)
    System.out.println("The sum is: " + (x + y));

3. The break and continue statements

Example:

   // Using the break statement in a for structure
   for (int x = 1; x <= 10; x++ ) {
      if ( x == 5 )
         break;    // break loop only if x is 5
      System.out.print(x + " ");
   }
   System.out.println();
   System.out.println("Broke out of loop at x = " + x );
 

Example:

 
// Using the continue statement in a for structure
int temp;
for (int x = 1; x <= 10; x++) {
      if (x == 5) {
         temp = x;
         continue;  // skip remaining code in loop for x=5
      }
      System.out.print(x + " ");
}
System.out.println();
System.out.println("Used continue to skip printing the value " + temp);
 

4. Some guidelines for choosing a looping statement:

5. Generating random numbers

Java provides several mechanisms for obtaining pseudorandom numbers  (seem to be random, but they are produced by an algoriyhm).

Option 1: Call the random method from the Math class --> obtain a random value of type double with the property  0.0 <= Math.random() < 1.0. This option provides a quick and easy way to get a random number that can be used in combination with multiplication to change the range of values.
Option 2: Objects of the class
Random generate pseudorandom numbers. The class Random is found in the java.util package, so you need to include in your program the statement:

        import java.util.*;
Examples:
        Random rand = new Random();
        int randNumber = rand.nextInt(10); // randNumber has a random value between 0 and 9
 

 

Method Name

Description

nextInt()

Returns a random integer

nextInt(MAX)

Returns a random integer x; 0 <= x <= MAX - 1

nextDouble()

Returns a random real number x; 0.0 <= x < 1.0

nextBoolean()

Returns a random logical value (true OR false)

Common usage: to generate random integer numbers in a range. NOTE: use class constants for the MIN and MAX values.

1. Generate a random number x, in  range [0, MAX] (0 <= x <= MAX):
    int n = rand.nextInt(MAX + 1);
Examples:

2. Generate a random number x, in  range [MIN, MAX] (MIN <= x <= MAX):
    int n = rand.nextInt(MAX - MIN + 1) + MIN;
Examples:

7. Some Exercises:

1. What is the output?

for (int i = 7; i > 3; i--)
    System.out.print(i + " ");
System.out.println();

2. What is the output?

for (int i = 1; i < 10; i = i + 2)
    System.out.print(i + " ");

3. What is the output?

int sum = 0;
for (int i = 1; i < 6; i++){
    sum = sum + i;
    System.out.println("Sum  = " + sum);
}

4. What is the output now?

int sum = 0;
for (int i = 1; i < 6; i++)
    sum = sum + i;
System.out.println("Sum  = " + sum);

5. What is the output?

int x = 1;
for (int i = 1; i < 6; i++) {
    System.out.print(x + " ");
    x = 2 * x + 1;
}
System.out.println(x);

6. Find the errors:

1. for (j == 0, j < n,  j ++) {...

2. for (j < n; j --);
     System.out.println(j);

3. for (int j = 7; j > 3; j--)
     k = k + j;
     System.out.println(j + " " + k);

7. What is the output?

int i, j;
for (i = 1 ; i <= 3 ; i++ ){
     System.out.print(i + " ");
     for (j = 1 ; j <= 5 ; j++ )
          System.out.print(j + " ");
     System.out.println();
}

8. What is the output?

//LECTURE #7: EXAMPLE #8
import java.util.*;
public  class Ex8{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int how_many;
        System.out.print("How many rows/columns box(>= 5): ");
        how_many = input.nextInt();
        while(how_many < 5) {
            System.out.print("ERROR! Should be >= 5. Reenter: ");
            how_many = input.nextInt();
        }
        for (int row = 1; row <= how_many; row++) {
            for (int column = 1; column <= how_many; column++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
OUTPUT:
How many rows/columns box(>= 5): 3
ERROR! Should be >= 5. Reenter: 6
******
******
******
******
******
******

9. What is the output?

//LECTURE #7: EXAMPLE #9
import java.util.*;
public  class Ex9{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int how_many;
        char what;
        System.out.print("How many rows/columns box(>= 5): ");
        how_many = input.nextInt();
        while(how_many < 5) {
            System.out.print("ERROR! Should be >= 5. Reenter: ");
            how_many = input.nextInt();
        }
        for (int row = 1; row <= how_many; row++) {
                if(row % 2 == 0)
                    what = '+';
                else
                    what = '-';
            for (int column = 1; column <= how_many; column++) {
                System.out.print(what);
            }
            System.out.println();
        }
    }
}
OUTPUT:
How many rows/columns box(>= 5): 4
ERROR! Should be >= 5. Reenter: 6
------
++++++
------
++++++
------
++++++

Change the program so that '+' and '-' alternate /each row.

10. What is the output?

//LECTURE #7: EXAMPLE #10
public  class Ex10 {
    public static final int MAX = 5;
    public static void main(String[] args) {
        for (int row = 1; row <= MAX; row++) {
            for (int column = 1; column <= MAX; column++) {
                System.out.print("|");
                for (int dashes = 1; dashes <= 2; dashes++) {
                    System.out.print("_");
                }
            }
            System.out.println("|");
        }
    }
}
OUTPUT:
|__|__|__|__|__|
|__|__|__|__|__|
|__|__|__|__|__|
|__|__|__|__|__|
|__|__|__|__|__|

11. What is the output?

//LECTURE #7: EXAMPLE #11
public  class Ex11 {
    public static void main(String[] args) {
        int j,k;
        int n = 0;
        for (j = 0; j < 6; j++) {
            System.out.println("j = " + j);
            for (k = 0; k <j; k++) {
                System.out.print("\tk = " + k + " ");
                n++;
                System.out.print("\tn = " + n + "\n ");
            }
        }
    }
}
OUTPUT:
j = 0
j = 1
    k = 0  n = 1
j = 2
    k = 0  n = 2
    k = 1  n = 3
j = 3
    k = 0  n = 4
    k = 1  n = 5
    k = 2  n = 6
j = 4
    k = 0  n = 7
    k = 1  n = 8
    k = 2  n = 9
    k = 3  n = 10
j = 5
    k = 0  n = 11
    k = 1  n = 12
    k = 2  n = 13
    k = 3  n = 14
    k = 4  n = 15

12. What is the output?

//LECTURE #7: EXAMPLE #12
//TEST FOR break
public  class Ex12 {
    public static void main(String[] args) {
        int j,k;
        int n = 0;
        for (j = 0; j < 6; j++) {
            System.out.println("j = " + j);
            for (k = 0; k <j; k++) {
                System.out.print("\tk = " + k + " ");
                if(j == 3) {
                    System.out.print("\tbreak used here\n");
                    break;
                }
                n++;
                System.out.print("\tn = " + n + "\n");
            }
        }
        System.out.println();
    }
}
OUTPUT:
j = 0
j = 1
     k = 0  n = 1
j = 2
     k = 0  n = 2
     k = 1  n = 3
j = 3
     k = 0  break used here
j = 4
     k = 0  n = 4
     k = 1  n = 5
     k = 2  n = 6
     k = 3  n = 7
j = 5
     k = 0  n = 8
     k = 1  n = 9
     k = 2  n = 10
     k = 3  n = 11
     k = 4  n = 12

13.  Example of a Java program using a switch nested in a while loop. Change the loop from while  to  do-while.

//LECTURE #7: EXAMPLE #13
//Counting letter grades (switch)
import java.util.*;
public  class Ex13 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        char grade;
        int countA = 0; // number of A's
        int countB = 0; // number of B's
        int countC = 0; // number of C's
        int countD = 0; // number of D's
        int countF = 0; // number of F's

        System.out.print("Enter the letter grades (A,B,C,D,F; S to stop): ");
        grade = input.next().charAt(0); //initialize: priming read
        while(grade != 'S' && grade != 's'){ //test sentinel
            switch (grade){
                case 'A':
                case 'a':
                    ++countA;
                    break;
                case 'B':
                case 'b':
                    ++countB;
                    break;
                case 'C':
                case 'c':

          ++countC;

                    break;
                case 'D':
                case 'd':
                    ++countD;
                    break;
                case 'F':
                case 'f':
                    ++countF;
                    break;

           default:

                    System.out.println("Incorrect letter grade entered!");
           }
           System.out.print("Enter the letter grades (A,B,C,D,F; S to stop): )";
           grade = input.next().charAt(0);//update: next read
       }
       System.out.println("\nTotals for each letter grade are: ");
       System.out.println("A: " + countA);
       System.out.println("B: " + countB);
       System.out.println("C: " + countC);
       System.out.println("D: " + countD);
       System.out.println("F: " + countF);
    }
}

14.  Example of a Java program using random numbers.

//LECTURE #7: EXAMPLE #14
//Random numbers
import java.util.*;

public class Dice {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random rand = new Random();
        int user_number;
        int count = 1;
        int dice_number;
        System.out.println("Choose a number between 1 and 6 ");
        System.out.print("I will tell you after how many die rolls it will come up: ");
        user_number = input.nextInt();
        while(user_number < 1 || user_number > 6) {
          System.out.print("ERROR! Out of range. Reenter: ");
          user_number = input.nextInt();
        }
        do{
          dice_number = rand.nextInt(6) + 1;
          System.out.println("Die roll # " + count + " --- Die number: " + dice_number);
          count++;
        }while(dice_number != user_number);
        System.out.println("Your number came up after " + (count - 1) + " die rolls");
    }
}
OUTPUT:
Choose a number between 1 and 6
I will tell you after how many die rolls it will come up: 8
ERROR! Out of range. Reenter: 7
ERROR! Out of range. Reenter: 6
Die roll # 1 --- Die number: 4
Die roll # 2 --- Die number: 3
Die roll # 3 --- Die number: 2
Die roll # 4 --- Die number: 5
Die roll # 5 --- Die number: 4
Die roll # 6 --- Die number: 2
Die roll # 7 --- Die number: 3
Die roll # 8 --- Die number: 6
Your number came up after 8 die rolls


References:
[1] Building Java Programs: A Back to Basics Approach, by Stuart Reges, and Marty Stepp, Addison Wesley, 2008.
[2] Java Programming: From Problem Analysis to Program Design, by D.S. Malik, Thomson Course Technology, 2008