Back to all lessons


Lesson 7

Arrays


public class Main {
    public static void main(String[] args) {
        // change "type" for int, char, boolean etc.
        type[] nameOfArray = new type[sizeOfArray];
        // i.e.:
        int[] integerArray = new int[20];
        // 2-d array:
        double[][] _2dArrayOfDoubles = new double[20][10];
        // if you want to set value:
        int[] x = {1,2,3,4};
    }
}
            

public class Main {
    public static void main(String[] args) {
        // Prints a 'random' number in range [0, 100)
        System.out.println(
            Math.random()*100
        );
        // Prints a 'random' number in range [0, 99]
        System.out.println(
            (int)(Math.random()*100)
        );
    }
} 
Task 0

There is an array containg 11 elements. What are possible indexes I can use? (what value can I put in place of question mark: array[?])

Task 1

Declare an array of any type (e.g. int).

Task 2

Declare one dimensional array of int type which contains 10 elements.

Then print an information confirming the length of the array.

Task 3

Declare one dimensional array of int type which contains 10 elements.

Then fill in the array with random values 0 or 1.

Task 4

Write a program that counts how many 0's and 1's are in the array from the previous task.

Task 5

Create 2D array and display it as a table. Value of each element should be a sum of row and column index.

Task 6

There is a 20 elements array. Find the index of the lowest value.

Task 7

Create a character array (char as type) and put there your nickname / name.

Then display whole message (character by character).

Task 8

Display your nickname / name, but in reversed way.

Task 9

Check if a text written as char array is a palindrome.

Task 10

Create an array that contains bits representation of an integer.

i.e. 2353 -> [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,1,0,0,0,1]

Disclaimer: it is not about printing, but creating a new array

Task 11

Create a 2D array, that each row has a different length.

Display all elements.

Task 12

Display sum and average of all elements of an integer array.

Values of array should be generated randomly in range set by user.

Task 13

Create a program, that sorts an integer array.

Task 14

Create Tic Tac Toe.

Some hints:

  1. Store a state of the board in 9 elements array.
  2. Read an integer, which tells we want to put 'x' or 'o'
  3. Until game is not over, print board and wait for move.
  4. Check for winning (losing) condition.