Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java LESSON 4 Arrays.

Similar presentations


Presentation on theme: "Java LESSON 4 Arrays."— Presentation transcript:

1 Java LESSON 4 Arrays

2 Today Why Arrays What are Arrays How to use Arrays When to use Arrays

3 Why Arrays ? Whenever we want to store lots of information of the same type, arrays are a simple way to do that: Example: Analyse the annual rainfall over a period of 90 years: "Traditional" solution Solution using arrays float rainFall_1; float[ ] rainFall = new float[ 90 ]; float rainFall_2; float rainFall_3; float rainFall_4; float …….. float rainFall_90;

4 Another Example Store the names of 120 students
"Traditional" solution Solution using arrays String student_1; String[ ] student = new String[ 120 ]; String student_2; String student_3; String student_4; String …. …. String student_120;

5 Not Only Storing - Accessing
Initialising the rain fall to zero: "Traditional" solution Solution using arrays rainFall_1 = 0.0; rainFall_2 = 0.0; for(int i=0; i<90; ++i) { rainFall_3 = 0.0; rainFall[ i ] =0.0; rainFall_4 = 0.0; } …….. ……. rainFall_90 = 0.0;

6 Why Arrays - Summary Arrays are useful if we want to
store lots of information of the same type (int, float, Objects (!), etc……) Arrays require MUCH less typing when declaring them initialising them accessing them

7 Using Arrays: Declaration & Initialisation
1 "Traditional" Way Using Arrays (2 step method) Step 1 (declare): float rainFall_1; standard Java: float [ ] rainFall; float rainFall_2; (‘C’ alternative: float rainFall[ ];) float …... Step 2 (allocate space): rainFall = new float [ 90 ];

8 Using Arrays: Declaration & Initialisation
2 "Traditional" Way Using Arrays (single step) Step 1 & Step 2 in one go (i.e. declare and allocate space) float rainFall_1; float rainFall_2; float[ ] rainFall = new float[ 90 ]; float ....

9 Using Arrays: Declaration & Initialisation
"Traditional" Way Using Arrays rainFall_1 = 0.0; for(int i=0; i<90; ++i) { rainFall_2 = 0.0; rainFall[ i ] =0.0; }

10 Task Declare an array called 'messages' which will hold message Strings String[ ] messages; Allocate space for 100 messages messages = new String [100]; Do the same as above, but declare and allocate space in one go String[ ] messages = new String [100];

11 Accessing Array Elements
To STORE information in an array element: rainFall [ 5 ] = 20.5; '5' is the INDEX To RETRIEVE information from an array element: float rF; rF = rainFall [ 5 ]; System.out.println( rF );

12 The Problem with Indices
Humans start counting at '1': ,2,3,4,…… Computers start counting at '0': 0,1,2,3,…… The FIRST year of rainFall is therefore stored in rainFall[ 0 ] The LAST of the 90 years is stored in rainFall[ 89 ]

13 The Problem with Indices (cont)
If you declare an array of size 50: char [ ] sentence = new char [ 50 ]; The array can indeed hold 50 characters The last character is stored in sentence[ 49 ] If you try to access sentence[ 50 ] (which is the 51st element) you get an 'exception'.

14 Practical Advice Try to use arrays in connection with CONSTANTS
static final int YEARS=90; // global, outside methods float [ ] rainFall = new float [ YEARS ]; //inside main for(int actYear=0; actYear<YEARS; ++actYear) { rainFall[ actYear ] =0.0; } Why is that good practice? code maintenance minimising errors readability

15 Task static final int YEAR=12; // outside main int i, sum=0, pay=1000; // inside main int [ ] monthlyPay = new int [YEAR]; for( i=0; i<YEAR; ++i) { monthlyPay[ i ] = pay; pay=pay+10; } sum = sum + monthlyPay[ i ]; System.out.println( sum ); Declare an integer array called 'monthlyPay' of constant size 12. In the first month the pay is Every month the pay goes up by 10 (I wish…). Fill the array with these values for one year. Calculate the sum of all pay during the year. 12 660

16 Task An integer array called 'values' of constant size 10 holds random numbers between 0 and 1000. Find the largest one. Find the smallest one. static final int SIZE = 10; // outside main int [ ] values = new int [SIZE]; // hidden code here that puts // random numbers into values[ ] // your code starts here int min=1000, max=0; for (int i=0; i<SIZE; ++i) { if (values[ i ] < min) { min=values[ i ]; } if( values[ i ] > max) { max=values[ i ]; } // end of for loop

17 A Mystery Solved public class ParamListTest {
public static void main( String args[ ] ) { System.out.println("Parameter 1: " + args[0] ); System.out.println("Parameter 2: " + args[1] ); System.out.println("Parameter 3: " + args[2] ); If you call the compiled program ParamListTest.class like this.... java ParamListTest How are you the program will print this: Parameter 1: How Parameter 2: are Parameter 3: you

18 Review Quiz: What is wrong here?
public class PrintStudMarks { // global constant, max. number of students static final max-stud =100; static [ ] marks = new int [ max-stud ]; public static void main( String args[ ] ) { marks=readMarksFromFile(); if( args[0] == "All" ) { for(int i=0; i<=MAX_STUD; ++ i) { System.out.println(marks[ i ] ); } } // end of 'if All' if( args[0] == '1' ) { System.out.println( marks[ 1 ] ); if( args[0] == "2" ) { System.out.println( marks[ 2 ] ); should be in uppercase and no '-' static final int MAX_STUD=100; static int [ ] marks = new int [ MAX_STUD ]; type of constant missing -> int How do you start this program if you want to print all marks? java PrintStudMarks All i<= should be i< otherwise crash '1' is a char, should be String: "1" "1" actually prints the SECOND entry in marks[ ], "2" the third. 2/23/2019

19 Now: Array Actions Insertion Deletion Sorting Multi-dimensional

20 Prepare an Array Declare an array of size 10: int A_SIZE = 10;
int [ ] a = new int [ A_SIZE ]; Read some values: int i=0; while (i < A_SIZE) { System.out.println("Enter value " + (i+1) ); a[ i ] = UserInput.readInt(); ++ i; }//end while

21 Insert a New Number at Index 3
Values 10 1 12 2 4 3 8 15 5 22 6 53 7 44 9 Shift: A_Size=10 insertPos=3 for ( int i=A_SIZE-1; i>insertPos; --i) { a [ i ] = a [ i-1 ]; } for ( int i=insertPos; i<A_SIZE; ++i) { a [ i+1 ] = a [ i ]; } ? Insert: a [ insertPos ] = 100; 100 i=4 8 i=5 15 i=6 22 i=7 53 i=8 12 i=9 44 (i.e. the last array entry) is lost! >>>>> Collections

22 Insert a NEW Number at Index 3
Values 10 1 12 2 4 3 8 15 5 22 6 53 7 44 9 Would this work ? for ( int i=insertPos; i<A_SIZE; ++i) { a [ i +1] = a[ i ]; } i=3 Possible Solutions? Create a larger array and don’t use all the elements initially. Or use other storage systems that can be resized at run time. 8 i=4 8 i=5 8 i=6 8 i=7 8 i=8 8 i=9 8 Array overflow! >> Collections

23 Array Actions Insertion Deletion Sorting Multi-dimensional

24 Delete Number at Index 3 Index Values Shift: A_Size=10 delPos=3
10 1 12 2 4 3 8 15 5 22 6 53 7 44 9 Shift: A_Size=10 delPos=3 for ( int i=delPos; i<A_SIZE-1; ++i ) { a [ i ] = a[ i+1 ]; } 15 i=3 Insert: a [ A_SIZE-1 ] = 0; 22 i=4 53 i=5 i=6 12 i=7 44 i=8 6

25 Array Actions Insertion Deletion Sorting Multi-dimensional

26 Sorting Algorithms Bubble sort (simple, slow: time prop.N2)
Insertion sort (as above) Shell sort (N log2 N) Merge sort (N log N) Heapsort Quicksort Bucket sort Radix sort Distrib. sort etc . . . N N2 N log2 N N log N 5 25 2.4 3.5 10 100 1,000 400 200 1000 1 m 9,000 3,000

27 Bubble Sort Swapped = True While Swapped swapped = false
for each i from 0 to A_SIZE-2 if A[i] > A[i+1] then swap( A[i], A[i+1] ) swapped = true end if end for End While

28 Bubble Sort How to Swap ?

29 Bubble Sort while and for While (swapped) swapped = false
final int A_SIZE = 10; int [ ] A = new int[A_SIZE]; bool swapped; int temp; while and for While (swapped) swapped = false for each i from 0 to A_SIZE-2 if A[i] > A[i+1] then swap( A[i], A[i+1] ) swapped = true end if end for while swapped while (swapped){ swapped = false; for ( int i=0; i<A_SIZE-2; ++i ) if ( A[i] > A[i+1] ) { temp = A[i]; A[i] = A[i+1]; A[i+1] = temp; swapped = true; } } }//end while

30 Today Insertion Deletion Sorting Multi-dimensional

31 Multi-Dimensional Arrays
Arrays can also be 2 dimensional: int [ ][ ] rectangleDims = new int [10][10]; In fact, they can have as many dimensions as you like: int [ ][ ][ ][ ] vastArray = new int [100][10][40][500]; ( that’s 20 million integers, or approximately 19.5 MB)

32 Access: Nested Loops Write Example: final int X_DIM=10, Y_DIM=20;
int [ ][ ] twoDimArr = new int [X_DIM][Y_DIM]; for( int i=0; i<X_DIM; ++i ) { for( int u=0; u<Y_DIM; ++u ) { twoDimArr[ i ][ u ] = 0; }

33 There is Another Way.... Arrays (done)
known number of items in one data structure Collections (next lesson) unknown number of items in one data structure dynamic allocation other differences to Arrays

34 END OF LESSON 4


Download ppt "Java LESSON 4 Arrays."

Similar presentations


Ads by Google