Examples

This section includes a few more examples of full programs that use arrays.

Example 1: find average, minimum, and maximum

Suppose we want to write a program that asks the user for 20 numbers (doubles), and that calculates and prints the average, minimum, and maximum number from the user.

import java.util.*;

public class Example1 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);

        //get 20 numbers from the user
        double[] nums = new double[20];
        for (int i = 0; i < nums.length; i++) 
        {
            System.out.print("Enter the next number: ");
            nums[i] = s.nextDouble();
        }

        //find the average
        double sum = 0;
        for (int i = 0; i < nums.length; i++) 
        {
            sum += nums[i];
        }
        double average = sum / nums.length;
        System.out.printf("Average: %d%n", average);

        //find the minimum
        double min = nums[0];
        for (int i = 1; i < nums.length; i++) 
        {
            if (nums[i] < min) min = nums[i];
        }
        System.out.printf("Minimum: %d%n", min);

        //find the maximum
        double max = nums[0];
        for (int i = 1; i < nums.length; i++) 
        {
            if (nums[i] > max) max = nums[i];
        }
        System.out.printf("Maximum: %d%n", max);
    }
}

It turns out that we don’t need to write separate code to calculate the average, minimum, and maximum. We can combine those steps into a single loop. (We also don’t need to store the numbers in an array before doing our calculations, but we’ll keep that part since it’s the focus of this chapter.) Here is a shorter way to write the same program:

import java.util.*;

public class Example1 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);

        //get 20 numbers from the user
        double[] nums = new double[20];
        for (int i = 0; i < nums.length; i++) 
        {
            System.out.print("Enter the next number: ");
            nums[i] = s.nextDouble();
        }

        //find the average, minimum, and maximum
        double sum = 0;
        double min = nums[0];
        double max = nums[0];

        //for the min/max, it doesn't *hurt* to start at i=0
        for (int 0 = 0; i < nums.length; i++) 
        {
            sum += nums[i];
            if (nums[i] < min) min = nums[i];
            if (nums[i] > max) max = nums[i];
        }

        double average = sum / nums.length;
        System.out.printf("Average: %d%n", average);
        System.out.printf("Minimum: %d%n", min);
        System.out.printf("Maximum: %d%n", max);
    }
}

Example 2: reverse an array

In this example, we will write a full program that reverses an array in place. We will start by feeling the array with default values (we could get user input for the array values – the next steps would be the same in either case). Then, we will write the code necessary to switch array elements around so that they’re stored in reverse of the original order. Finally, we’ll print the resulting array to show that it will print in reverse order.

public class Example2 
{
    public static void main(String[] args) 
    {
        //could be any values, or could have gotten user input
        int[] nums = {2,4,6,8,10,12,14,16,20};

        //now reverse the order of the array elements
        //front starts at the beginning of the array and steps back
        //back starts at the end of the array and steps up
        //why do we only go halfway? Think about this.

        int back = nums.length-1;
        for (int front = 0; front < nums.length/2; front++) 
        {
            //at each step, swap the current front and back
            int temp = nums[front];
            nums[front] = nums[back];
            nums[back] = temp;
            back--;
        }
    }
}

Example 3: Tic-Tac-Toe

In this example, we will write a full Tic-Tac-Toe program between two players. We will use a 3x3 array of characters to store the board.

import java.util.*;
public class TicTacToe 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);

        char[][] board = new char[3][3];
        //fill with _ for blank spots
        for (int i = 0; i < 3; i++) 
        {
            for (int j = 0; j < 3; j++) 
            {
                board[i][j] = '_';
            }
        }

        //count how many moves have been made
        int moves = 0;
        //keep track of whose turn it is
        char turn = 'X';

        //print the initial board
        System.out.println("Current board: ");
        for (int i = 0; i < 3; i++) 
        {
            for (int j = 0; j < 3; j++) 
            {
                System.out.printf("%c ", board[i][j]);
            }
            System.out.println();
        }
        System.out.println();

        //keep playing while less than 9 moves
        while (moves < 9) {
            System.out.printf("%c, enter row: ", turn);
            int row = s.nextInt();
            System.out.printf("%c, enter column: ", turn);
            int col = s.nextInt();

            //check to see if that is a valid move
            if (row < 0 || row > 2 || col < 0 || col > 2) 
            {
                System.out.println("Invalid row/column");
            }
            else if (board[row][col] != '_') 
            {
                System.out.println("That spot is taken");
            }
            else 
            {
                //it was a good move
                board[row][col] = turn;

                //print the board
                System.out.println("Current board: ");
                for (int i = 0; i < 3; i++) 
                {
                    for (int j = 0; j < 3; j++) 
                    {
                        System.out.printf("%c ", board[i][j]);
                    }
                    System.out.println();
                }
                System.out.println();

                //check for a winner
                boolean win = false;
                for (int i = 0; i < 3; i++) 
                {
                    //found 3 on a row
                    if (board[i][0] == board[i][1] &&
                    board[i][1] == board[i][2] &&
                    board[i][0] == turn) win = true;

                    //found 3 on a column
                    if (board[0][i] == board[1][i] &&
                    board[1][i] == board[2][i] &&
                    board[0][i] == turn) win = true;
                }

                //found 3 on a \ diagonal
                if (board[0][0] == board[1][1] &&
                board[1][1] == board[2][2] &&
                board[0][0] == turn) win = true;

                //found 3 on a / diagonal
                if (board[2][0] == board[1][1] &&
                board[1][1] == board[0][2] &&
                board[2][0] == turn) win = true;

                if (win) 
                {
                    System.out.printf("%c wins!%n", turn);
                    //end the game
                    break;
                }

                //switch whose turn it is
                if (turn == 'X') turn = 'O';
                else turn = 'X';

                //increment number of moves
                moves++;
            }
        }

        //if moves made it to 9, must be a tie
        if (moves == 9) System.out.println("Tie game.");
    }
}