if, arrays, and for

Continuing through the textbook, we'll try to cover Chapters 8 and 9.

 

Conditional execution: the if statement

An if statement specifies that its body should only be executed if its condition is true:
		if ( <condition> ) {
		     <body>
		}
It looks a lot like a while loop, but it doesn't loop.

Example: code fragment for computing absolute value:

		double abs = num;
		if(num < 0.0) {
		    abs = -num;
		}

The else clause

This lets you specify what to do if the condition is false:
		if ( <condition> ) {
		     <true-body>
		} else {
		     <false-body>
		}

Example: code fragment for finding the maximum of two integers:

		int max;
		if (x > y) {
		    max = x;
		} else {
		    max = y;
		}

You can also use else if to string a number of possibilities together:

		io.println("Guess a number.");
		int guess = io.readInt();
		if (guess < 21) {
		    io.print("That's way too small.");
		} else if (guess < 23) {
		    io.print("That's too small.");
		} else if (guess > 23) {
		    io.print("That's too big.");
		} else {
		    io.print("That's just right!");
		}

The break statement

The break statement is very simple, just break;
It causes the program to immediately skip to the end of the innermost loop surrounding it.

We can demonstrate the break statement in a program for testing an integer for primality, using the Prime-Test-All algorithm from Chapter 2:

	import pgss.*;

	public class Primality {
	    public static void main(String[] args) {
		IOWindow io = new IOWindow();
		io.print("What do you want to test? ");
		int to_test = io.readInt();
		int i = 2;
		while(i * i <= to_test) {
		    if(to_test % i == 0) {
		        io.println("It is not prime.");
			break;
		    }
		    i++;
		}
		if(i * i > to_test) {
		    io.println("It is prime.");
		}
	    }
	}

 

Arrays

An array is an object that can hold a sequence of values.
Arrays are very handy; for example, if you have 100 data points, you wouldn't want to have to name 100 variables x1, x2, ... !
(Or even worse, suppose you wanted to read in the number of data points at the start of execution.)
Each member of the sequence of values is called an array element.

You use square brackets to declare that a variable is an array type. For example, suppose you wanted an array of real numbers called score:

		double[] score;
We use the new keyword to assign an actual new array to a variable of type array:
		score = new double[3];
		score = new double[2 * num_students];

To actually use an array, you use array indices within []:

		double[] score = new double[3];
		score[0] = 97.0;
		score[1] = 83.0;
		score[2] = 66.0;
		io.println("Average = " + ((score[0] + score[1]
						+ score[2]) / 3.0));

The real value of arrays comes when you use a variable or expression as the index. For example, we can now read in an arbitrary series of numbers and reverse them:

	import pgss.*;

	public class PrintReverse {
	    public static void main(String[] args) {
		// create the array
		IOWindow io = new IOWindow();
		io.print("How many scores? ");
		int num_scores = io.readInt();
		double[] scores = new double[num_scores];

		// fill the array
		io.println("Type the scores now.");
		int i = 0;
		while(i < num_scores) {
		    scores[i] = io.readDouble();
		    i++;
		}
		
		// print it in reverse
		io.println("Here they are in reverse order.");
		i = num_scores - 1;
		while(i >= 0) {
		    io.println("  " + scores[i]);
		    i--;
		}
	    }
	}
We could not have done this until now!

The length attribute

There's a special technique available to get the length of an array:
		while(i < scores.length) {

 

The for loop

The for loop is used for iterating or stepping through all the values in some set, and executing a group of statements for each value:

		for (<initial>; <condition>; <update>) {
		    <body>
		}
This is similar to a particular while loop:
		<initial>;
		while ( <condition> ) {
		    <body>
		    <update>;
		}
We can use a for loop to calculate the factorial of an integer:
		double fact = 1.0;  // we begin with 1
		for(int i = 1; i <= num; i++) {
		    fact *= i;
		}
		io.println(num + " factorial = " + fact);
The for loop is often used when working with arrays.
Here is PrintReverse written using for loops:
	import pgss.*;

	public class PrintReverse {
	    public static void main(String[] args) {
		// create the array
		IOWindow io = new IOWindow();
		io.print("How many scores? ");
		int num_scores = io.readInt();
		double[] scores = new double[num_scores];

		// fill the array
		io.println("Type the scores now.");
		for(int i = 0; i < scores.length; i++) {
		    scores[i] = io.readDouble();
		}
		
		// print it in reverse
		io.println("Here they are in reverse order.");
		for(int i = scores.length; i >= 0; i--) {
		    io.println("  " + scores[i]);
		}
	    }
	}