More Iteration Structures

definite loop: a loop that executes a known number of times.

indefinite loop: a loop that does not execute a known number of times. Instead, an indefinite loop executes until some condition is satisfied.

The while statement

while(you are hungry)
   eat another bite

while(there are more lines of text in the input file)
    read the next line from the file


How it works:
A while statement executes a block of code repeatedly, as long as the <condition> is true. The condition is evaluated before each execution of the statements in the loop body, and if the condition evalutes to false, execution of the while loop terminates.

int count = 1;
while(count <= 5)
System.out.println("count is " + count);

int num = 1;
int sum = 0;

// add nums from 1 to 5 to sum
while(num <= 5)
    sum = sum + num; 
    num++;  // what happens if I omit this??
System.out.println("The sum of the first 5 positive integers is " + sum);

Question: Consider the following code:
int x = 5;
int y = 13;
while (x < y) {
   x += 2;
   y -= 2;

How many times is the phrase "loop-di-loop" printed?
A.  1
B. 2
C. 3
D. 4
E. 5

Practice with while loops

Exercise: Write a while loop that prints the squares of the integers from 1 to 15 to the console window, separated by spaces.

Exercise: Prompt the user to enter a sequence of positive integers, one at a time. The user enters zero or a negative number to quit. Print the sum of the positive integers.

Sentinel Loops

Our last exercise is an example of a loop called a sentinel loop:
The loop gets and processes values until seeing a special value called the sentinel, that indicates that processing should stop.

Note: In the above exercise, the sentinel is either 0 or a negative number.

In general, the psuedo-code for a sentinel loop is like this:

read the first value
while value is not the sentinel:
     process the value
     read the next value

Example: Write a program that prompts the user for input until a positive integer is entered. Once a positive integer is entered, the program should print the square of that integer. For now, we will assume that all values entered by the user are integers.

Sample Output:
Enter a positive integer: -44
Not a valid input. Positive integer, please: 0
Not a valid input. Positive integer, please: 5
The square of 5 is 25.

for and while Loop Example

Consider this for loop:
for(int i = 1; i <= 10; i++)

What is an equivalent while loop?

int i = 1;
while(i <= 10)

while Loops and for Loops

for(<init>; <condition>; <update>)
    <body statement(s)>

Equivalent while loop:

    <body statement(s)>

Review Question

Consider the following for loop:

for(int i = 2; i <= 20; i+=3)

Which while loop below is equivalent?

A.                                                      B.
int i = 2;                                            int i = 2;
i += 3;                                               while(i <= 20) {
while(i <= 20) {                                     i+= 3;
   System.out.println(i);                           System.out.println(i);
   i += 3;                                            }

C.                                                      D. A and B
int i = 2;
while(i <= 20) {                                E. A, B and C.
i += 3;

Testing Validity of User Input

Method Description
hasNext() returns true if there's another token that can be read as a String (only useful for file input - more on this later)
hasNextInt() returns true if next token can be read as an int
hasNextDouble() returns true if next token can be read as a double
hasNextLine() returns true if there's another line of input that can be read as a String (only useful for file input)

Example: Write a program that asks the user for 10 numbers, and then prints a message indicating whether each is an integer or a floating-point number.

Scanner reader = new Scanner(;
System.out.print("Enter 10 numbers: ");
for(int i = 1; i <= 10; i++)
       System.out.println(reader.nextInt() + ": is an integer");
       System.out.println(reader.nextDouble() + ": is a floating point number");

The do-while statement

Like a while loop, except the loop body is always executed once.

while (<condition>) ;

How it works:

Psuedo-code Example:
    start the car's engine
while(engine is not running);


int val = 5;

// what does this loop do?
while(val> 1);

Review Question

Consider the do while loop below:

do {
   y = x+5;
   x = x+1;
} while(x < 8);

Which code below is equivalent?

A.                                  B.
y = x+5;                            while(x < 8) {
x++;                                      y = x+5;
while (x < 8) {                       x = x+1;
   y = x+5;                          }
   x++;                                y = x+5;
}                                         x = x+1;

C.                                  D. A and B
while(x < 8) {
   y = x+5;                    E. A, B and C

Practice Problems

Exercise: Write a program that reads integers from the user until the user enters 0. Then the program prints the number of positive integers and the number of negative integers that were entered.

Exercise: Write a method that takes two integer arguments, and returns true if both arguments are positive and false otherwise.

Exercise: Write a program that reads numbers from the user until the user enters "stop" (regardless of case). When the user enters "stop", print the sum of the numbers.

Exercise - Random class review: Write a few lines of Java code that print:
a) a random integer 0 to 20
b) a random integer 2 to 5
c) a random integer -10 to 10
d) a random even integer from 2 to 18

Exercise: Convert the following for loop to a while loop:
double sum = 0;
for(int i = 0; i <= 1000; i++)
    sum = sum + i;

Exercise: Write a program that prompts the user to enter positive integers (or 0 or a negative number to stop). Print the largest positive integer that was entered. (What is the sentinel??)

Converting Strings to Numeric Types

Two Static Methods:

String str = "14.3";
double strDouble = Double.parseDouble(str); // 14.3

String myString = "123";
int myInt = Integer.parseInt(myString); // myInt is 123