# The while statement

• Introduction

• So far, our computer programs do not achieve "grandiose" task mainly because we have not learned the most powerful statment in a programming language:

while statement

• After learning this powerful statement, we will be able to write every possible program imaginable....

Also, the examples and programming assignments will get much more exciting...

• We will learn 2 more statements in this chapter:

• The while   statement
• The for   statement

NOTE:

• I will use Mathamatically oriented examples to teach the remainder of the course (while the book uses an investment class).

I do this because:

• Many of the students are Math majors and they may find investment calculation less useful.
• You can see more examples of programs (if in addition, you also read the book) - you will be more familiar with the advanced statement is you learn by examples

• General information on while, for and do-while statements

• The while   statement, for   statement and do-while statements are known as loop statements because they execute a statement more than one time

 The loop statements lets a computer program execute a statement (usually a compound statement) multiple times until a condition is satisfied

IMPORTANT

• Syntax of the while statement

• The syntax structure (the way to tell the computer) of the while   statement is as follows:

 ``` while ( Condition ) ONE-single-statement // While body ```

• Again, the key to understanding the while statement is by working with many examples.

When you have written enough while   statements, I am sure that you will not only memorize this syntax, but can use it effectively.

IMPORTANT

• The meaning of the while   statement is:

 The Condition clause specifies a condition. (A condition is very similar to a Mathematical relation, e.g.: x > 0 or x + y < 0 , etc.) If the Condition clause is satisfied , then the statement part is executed . After executing the statement, the computer goes back to the beginning and evaluate the Condition clause again. The statement part is executed as long as the Condition clause is TRUE When the Condition clause is NOT satisfied , then the statement part is SKIPPED OVER, and the program continues with the statement that follows the WHILE statement.

• Infinite loop....

• It is conceivable (and many new programmers will make this error) that the program executes the statement part of the WHILE statement without the possibility of ever stopping...

• Example:

 ``` int x = 1; while ( x < 100 ) System.out.println("x = " + x); ```

• So the WHILE statement is powerful...

And with greater power, there is also greater responsibility... (Spiderman's Uncle)

The first and foremost responsibility is to make sure that the statement inside the while loop will affect the condition so that the while loop will terminate !!!

• Example:

 ``` int x = 1; while ( x < 100 ) { System.out.println("x = " + x); x++; } ```

• Example Program: (Demo above code)

• (1) Example of while statement

• Problem statement:

 Write a program that reads in an integer number n and print all dividers of n (A divider is an integer number that divide n with remainder zero, e.g., 4 is a divider of 36)

• Fact 1:

All divider of n are less than or equal to n.

• Fact 2:

A number f is a divider of n, if and only if:

 ``` n % f == 0 ```

• The operation "n % f" gives the remainder of the division "n / f"

• The computer is not intelligent, but it is FAST

Many problems are solved with the computer by trying every possible value

The solutions are identified by testing whether a value works

• The "find all divider" problem can be solved with a computer as follows:

 ``` public class FindDividers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; int f; System.out.print("Enter integer: "); n = in.nextInt(); // ---------------------------------------------------------- // Try all number from 1 to n to see if it is a divider of n // ---------------------------------------------------------- f = 1; // start while ( f <= n ) { if ( n % f == 0 ) System.out.println(f); f++; } } } ```

• After reading in a value and assigning it to n, the program proceeds to look for dividers of n (red section)

• The variable f starts with the value 1 (f = 1;)

Then the while statement is executed...

• As long as f is less or equal to n, the compound statement
```      {
if ( n % f == 0 )
System.out.println(f);

f++;
}
```
is executed.

This compound statement checks if the remainder of the division n/f is zero ( n % f == 0 )

If so, then f is a divider of n, the number f is printed (otherwise, it is not printed).

• After this, the statement f++; increments f by 1; and the while statement is repeated with the NEW value f !!!

So the first time, f = 1, the next time f = 2, and the time after that, f = 3, and so on.

• The while statement stops when the test:
```	while ( f <= n )
...
```
is false.

This will happen when f = n + 1.

So, the while statement will be executed for f = 1, f = 2, ..., f = n.

In other words, the test n % f == 0 is tried using f = 1, 2, 3, ..., n and the values that succeeds (remainder is indeed 0) will be printed.

• Example Program: (Demo above code)

• (2) Example of while statement

• Problem statement:

 Write a program that reads in an integer number n and print the factors of n Examples: The factors of 36 are: 2, 2, 3, 3 (Because 2 x 2 x 3 x 3 = 36) The factors of 45 are: 3, 3, 5 (Because 3 x 3 x 5 = 45)

IMPORTANT

• Advice: How to write a computer program

 The first step towards writing a program to solve a problem is to write down each step that you would perform when you solve the problem The second step towards writing a program to solve a problem is to find the repeating pattern in the steps. Use concrete examples to discover steps 1 and 2 Use more than 1 example if necessary to discover the pattern... Use psuedo code (English instructions that resemble Java statements) to express your thought - it is easier to turn psuedo code into Java statements.

• You programming skills can only by honed by practice:

There is no such thing as a "naturally born programmer"

I can tell you from personal experience that unless you write on your own at least 10 "difficult" programs, you will not become a good programmer. (By difficult program I do not mean the ones you have seen so far, these are "toys". BTW, you won't see any "difficult" program in CS170, you need to take CS171, CS424, and other higher level classes)

• Discovering the steps you need to do to factor a number

 Example: factor 36 ``` n = 36 try factor 2 36/2 = 18 remainder 0, good ---> 2 n = 18 try factor 2 18/2 = 9 remainder 0, good ---> 2 n = 9 try factor 2 9/2 = 4 remainder 1, no good try factor 3 9/3 = 3 remainder 0, good ---> 3 n = 3 try factor 3 3/3 = 1 remainder 0, good ---> 3 n = 1 stop ! ```

Another example

 Example: factor 45 ``` n = 45 try factor 2 45/2 = 22 remainder 1, no good try factor 3 45/3 = 15 remainder 0, good ---> 3 n = 15 try factor 3 15/3 = 5 remainder 0, good ---> 3 n = 5 try factor 3 5/3 = 1 remainder 2, no good try factor 4 5/4 = 1 remainder 1, no good try factor 5 5/5 = 1 remainder 0, good ---> 5 n = 1 stop ! ```

• Write down the steps that you do to factor a number n

1. Start with factor f = 2

2. Divide n by f.

3. Then:
```	If (remainder of division == 0)
update: n = n/f
(try the same f)
else
try f + 1
```

Sketch of algorithm:

 ``` input n; f = 2; while ( ??? when should we stop ??? ) { if ( n % f == 0 ) { print factor f; n = n / f ; // f unchanged ! } else { f++; } } ```

• When must we stop ???

• when n is equal to 1 !!!

Now write the algorithm in Java:

 ``` public class FindFactors { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; int f; System.out.print("Enter integer: "); n = in.nextInt(); // input n f = 2; // start while ( n != 1 ) { if ( n % f == 0 ) { System.out.println(f); n = n / f; } else { f++; // Try next number } } } } ```

• Example Program: (Demo above code)

• Packaging: How to make useful methods easily available

• Suppose we like to put the "find dividers" and "find factors" programs together for other people to use...

• As you know, a class is a container to hold useful operations/functions and these operations are usually related in one way or another. (see: click here )

• So if we want, we can put both algorithms together in a class - let's call that class "NumberStuff".

We have seen how to design a class in click here

So I will go through the design very quickly.

Design questions:

• What methods do you need:

• void findDividers()

No inputs needed (you will see why later)

• void findFactors()

No inputs needed (you will see why later)

• What information do we need to maintain so that the methods "findDividers()" and "findFactors()" can do their work ?

• int x (the number that you want to factor)

• What constructor methods do you need:

• NumberStuff(int n)

Initialize x with n

• The NumberStuff class:

 ``` public class NumberStuff { /** NumberStuff() * Constructor.... */ public NumberStuff(int n) { x = n; // Remember the number } /** findDividers() * Find all numbers that divides x */ public void findDividers() { int f; int n = x; f = 1; // start while ( f <= n ) { if ( n % f == 0 ) System.out.println(f); f++; } } /** findFactors() * Find all factors of number x */ public void findFactors() { int f; int n = x; f = 2; // start while ( n != 1 ) { if ( n % f == 0 ) { System.out.println(f); n = n / f; } else { f++; // Try next number } } } private int x; } ```

• Example how to use the NumberStuff class:

 ``` public class TestNumberStuff { public static void main(String[] args) { Scanner in = new Scanner(System.in); NumberStuff N; int n; System.out.print("Enter integer: "); n = in.nextInt(); N = new NumberStuff(n); System.out.println("The dividers of " + n + " are:"); N.findDividers(); System.out.println(); System.out.println("The factors of " + n + " are:"); N.findFactors(); } } ```

• Example Program: (Demo above code)

• Alternative ways to pass information to methods

• In the previous example, the methods findDividers() and findFactors() obtain the information from the instance variable x:

 ``` public class NumberStuff { public void findDividers() { ... uses instance variable x } public void findFactors() { ... uses instance variable x } private int x; // Instance variable } ```

• Because the findDividers() and findFactors() methods does not leave behind any long term information (information that persists even after the method terminates), the value x can be passed in through a parameter

 ``` public class NumberStuff { /** findDividers() * Find all numbers that divides x */ public static void findDividers(int x) { int f; int n = x; f = 1; // start while ( f <= n ) { if ( n % f == 0 ) System.out.println(f); f++; } } /** findFactors() * Find all factors of number x */ public static void findFactors(int x) { int f; int n = x; f = 2; // start while ( n != 1 ) { if ( n % f == 0 ) { System.out.println(f); n = n / f; } else { f++; // Try next number } } } } ```

• Example how to use the NumberStuff class:

 ``` public class TestNumberStuff { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n; System.out.print("Enter integer: "); n = in.nextInt(); System.out.println("The dividers of " + n + " are:"); NumberStuff.findDividers(n); System.out.println(); System.out.println("The factors of " + n + " are:"); NumberStuff.findFactors(n); } } ```

• Example Program: (Demo above code)

• Self Check

• What will the following program print:

 ``` int i; i = 7; while ( i < 10 ) { System.out.println( i ); i++; } ```

```	7
8
9
```

• What will the following program print:

 ``` int i; i = 7; while ( i < 10 ) System.out.println( i ); i++; ```

```        The program is read as:

while ( i < 10 )
System.out.println( i );

i++;

The program will therefore print:

7
7
..
.. (forever, will NOT STOP because i++ will not be executed !!!)
```

• What will the following program print:

 ``` int i; i = 7; while ( i < 10 ); { System.out.println( i ); i++; } ```

```	The program is read as:

while ( i < 10 )
;        		// Empty statement: does nothing...

{				// This is a compound statement
System.out.println( i );
i++;
}

So the program will not print anything, nor
will the program stop !!!

```