You are on page 1of 16
Arrays Dr. H. B. Prajopati 9 July "20, Core Java Technology Ty Why are Arrays Important in Programing? Suppose we have daly expenses in Rs We want to find out average daily expense We might think to create 30 variables (expensel, expense cexpense30) and then assign daly expenses to them We sum these 30 variables and calculate average by dividing the sum by 30 But this approach of programming has many limitations: 12 What if we é0 not have any expense on some days? teal days ae less than 30 or more than 307 we want to fing out average cay expense of 3 quarter or of hal year or of 2 whole year? “Therefore, we need efficient and organized approach to deal with » cllection of variables, L_L____v- d Outline of Presentation O Arrays Table of contents O Arrays 1 Declaring and Creating Arrays © Initializing and Processing Arrays Using Arrays for Problem Solving © Copying Arrays ‘& Anonymous Array and its Use 1 Array of Objects 1 Sorting Arrays © Searching Arrays @ Multi-imensional Arrays | Why are Arrays Important in Programing? Array isa data structure that provides a colecton of variables of ime data ype Ary alos aces ofeach variable ofthe cllcion wing the same «fray ues ines integer number to refer each vrible of he clection “Thus insaa of creating 30 separate variables, we create a single variable expense, which i an aay of double type (or expenses m fs) If we want to increase or decrease the numberof days, it can easily be elon ty modliVng the sizeof array in aray declaration, ata singe place. Java supponts to decide the siz of aay at rntine. sey 409 a Outline of Presentation Oras 1 Declaring and Creating Arrays a Declaring an Array 1 To use an array, frst we need to declare it. 1 The syntax to declare an aray i as follows Gatatypel] array 70R @atatype arrayName (1; | Vipreterred 1 The following cade declares an array of double data type. doublet 708 Gouble expense (1; expense; //prete . ST Array Representation expense rence 7 sorayreference variable expersel0l |__ 120.00 cexpensttl | 10530 ra een —— Bement: oe ewpense(28) 25.00 cexpense(28] 280.25 SL arama Outline of Presentation O Arrays © Initializing and Processing Arrays ae Creating Array © Java array is an object, so declaration does not allocate any space in memary te 18 We cannot assign value to uninitialized/uncreated array 18 We can use new operator te create the array with the following, syntax hold elements arraylane = nev davalype larraySizel) ‘2 We can combine declaration and creation in one statement oT a atype() arraylane = nov datatype larraySizel; datatype arraylane(] = nev datatype (arraysize): 1 The following code creates an array of type double of size 30 elements: Goubiel] expense = nev double (sol; A a as ay RL Sa a Array Declaration vs Array Creation [At the time of declaring an array Ac the time of cre After the array is created, its size cannot be changed. e size af array is not require ting an array, the size of array is required, But, we can cteate a nev array of new size and can assign it to the same reference variable, oo aa Initializing an Array '@ When an array is ereated, all the elements are assigned the default value depending upon the data type of the array. 1 0 for the numeric primitive data type variables = 1\u0000" for char variables ' false for boolean variables 1 null for objec: variables 1 Array is accessed using index te Array indices ar from 0 to atraySize- {For example for expense array, cxpense|2) will return the las element f We can aso assign new value cexpense[d]=120 00, 1» When invalid index (other than 0 to ataySize-1) is specified, exception vill accur For example, expense) wll Urow exception an array clement. Fer example I SS sy shy Size of Array and its use in Initialization 18 The size of an array is denoted by arrayObject length 12 After an aray is created, the length data field is assigned a value that indicates the number of elements in the created array. Imp. Note: length is afield, not a method-length() «8 For example, we can initialize expense array in the following way: [for Gat 1-0; expense [1] = best - 10; {Grade B if scare is >~ best - 20; Grade C sere is >= best - 30, 1 Grade D if sore is >= best - 40 Grade F othervise 2 We write a solution having the following steps: 1» The program prompts the user to enter the total number of students 1 The, the program prompts the user to enter score foreach student 1 Then, the rogram calculates and asigns grades 1 Finally, the program displays scores ane grades, _ re Program: Assigning Grades to Students, Slide - III System-out print ("Student -"+(ie1)+" Seore="): score (i]=input -nextInt () ifCacere il sbest) best = scoreLil x > i for(int 390; 1= best ~40) z geadeli) = '75 x cise 34 grade[s] = °F? 3 > Program: Assigning Grades to Students, Slide - V Error While Processing Array, Slide - | Error While Processing Array, Slide - II 18 While processing atray, a common error is accessing an array out of its bounds, «Valid indices are from 9 to arrayObject length-1 args) 120.25, fevetatie vold main (Stein Gouble[] expense={120.0, 45.50, 75, 100.03; for Gant imisi Lo Declare and Initialize Array of Objects 12 There is 2 difference between creating elements of an atray of, primitive types and an array of object types. © For an array of objects, we need one additional step of calling constructor for each element. 2|Student [] students students = now Stud . se Stud for Gnt i=0;i wubisc static Card{] gevcarapeck(0< Pivcard{] deck = new Gera (S21; 40 for(int i=0;1652; 140) ¢ a1 char au : 2 suiteh (1/13) ¢ 43| case 0: suite ty break; 4 case 1: suite = 'E?} break case 2: suite = 'C'! break? 46 case 3: suite = 'D'} break; a deck [i] = nev Card(auive, (in13) +1); 4 > Teturn deck > public static void printCardDeck (Card {I deck for (in 10; icdeck. Length si44)¢ LL =} Program: Random Shuffling of Playing Cards, Slide - VI IN Fo Program: Random Shuffling of Playing Cards, Slide - III else if(card¥o==12) x face = +g 2 else if (card¥o==13) 1 face = tk 2: else 24 faces" Error urn face s| public class DeckOfCards( public static void main( cara() deck=nu deck = getCaraDeck() yates our printin ("Cards before shuffling priatCardDeck (deck) ; BhuffleCarda (deck) Systen-out printin(*cards after shuffling: ") cring(] arge){ _ OT Program: Random Shuffling of Playing Cards, Slide - V System.out print (deck [i]+"\t"); Systen.out. printia() public static void shuffleCards (Card (] deck) { Card temp; for(int 90; i¢deck. Length sitt)< j = Cnt} (Wath. random () #deck. length); temp = deck [i] deck {i} = deck Lj]; @eck(j] = © _ OT Outline of Presentation Oras @ Sorting Arrays a Sorting Arrays Sorting is a common task in computer programming. E.g., sorting grades. Sorting can be done using many algorithms. We study selection sor. We study how the selection sort arranges numbers in an ascending order: «Selection sort finds the largest number in the it and places a last. © Then, from the remaining numbers (ie, excluding the last), the slgorithm fines the largest number and ples it ast (ie. secon last) 1 These suo steps (find max and place at last) are repeated until the remaining lst contains a single number. CS sa wy _ Selection Sort Algorithm array. lengeb-1ji>=i;1- select the largest number in array (1 fuap the largest with array[il. i necessary: : og. t—“—s~@™ Program: Selection Sort, Slide - II 15 16| 8 double currenttax; Snr currentMaxIndex for(int isarr-lenge spetza-9d 13 //tind the naxinin from arr[0..i 1 currentMax = arr[i]; 20 currentMaxIndex = 13 a for(int jaim 53920: if (eurrentwax < currentHax = currentéaxin 2 wi entNaxindex) if required 28 seCcurrentMaxindex: {= 104 29 arr[eurrentMaxindex] = arr [il 30 arr{i] = currentHax: 3 > Ta Selection Sort Orgnattanbes: a oH & BH [4] & place max — Fie ee =" BEGGS te oe mest Program: Selection Sort, Slide - class SelectionSert{ public static veld main(String(1_args){ @oubie(} spi= (7.6, 8.25, 6.75, 8.5, 7.0, 7.78); Syaten out printin(*sPI of students before sorting"); priatarray (spi) BortWithSelectionSert (epi) ; Systen.out printia("SPI of students after sorting "); printarray (spi)s > public static void printArray(double(] arr){ for(int 1*0;i _ LT ee Program: Linear Search, Slide - I! Public static int LimearSearch(int{] list, ant key) for Cint ist length site) 4 se Ckey ta) A sy ay I eT Program: Linear Search, Slide - II] 12 The element in the array can be present at any location array. 18 The execution time of the linear search increases linearly as the number of elements of the array increases 1 Linear search is inefficient for a large aay Binary Search Algorithm 18 The binary search algorithm first compares the key with the middle clement of the array 12 Three cases are possible: @ Ifthe key is matching withthe mile element, then the search ends and the index ofthe mide element is returned Q i the key is lower than the mide elem in the fist hal ef the aray. Q Ii the key is higher than the middle element, then further search is made in the second half of the aay Binary Search Algorithm ipprivave seatie inv binarySearch Gael int key, int lewer, iat upper){ Fetertrtast int mid = Clovertupper)/2; else if (keyiis return binarySea: upper); key 12 On average the algorithm needs to compare half of the elements in an vss ry _ rn further search is made a Binary Search Approach 18 Binary search is another approach to search an array. 18 For binary search the array elements need to be ordered, ascending or descending 12 We study the algorithm for binary search for which array elements are available in ascending order. Steps of Binary Search Algorithm vey 7 vi —- RES U U U lor ow per second al JJ, aea uu lover ald upper Program: Binary Search, Sllide - | Tapert javauvils; afclass BinarySearch{ public static void main(String(] args){ ‘Scanner input=new Scanner (Syatensin) ; int () abseatos = {11, 33, 55, 77, 98 tin} int key q Sysven.cut print ("Enter Rell Ke (search yoy key = input nextiat(); index = binarySearch (absentos, key); iGindex t= 1) Ft System.out print ("Rell No is found at Findex) j slse a4 System-out print ("Roll No is not found in the Tit"); _ Program: Binary Search, Sllide - II x public static Search(int (J list key) int lover=0; int upper=list. length -1; return binarySearch (ligt, upper); int bin 19 key, lover, ivate static int binarySearch (int () list int key, iat lever, int upper)< ss (aoweeoupper) int mid = (Loversupper) /2; Af Gkey==1ise [mia]) return mid; else if (weylist [mid]) key, lover _ Program: Binary Search, Sllide - IV “The binary search eliminates half of the elements after each comparison 1 For simplicity, let us assume n is power of 2. 18 After the first comparison, n/2 elements are left for further search, {After the second comparison, (n/2)/2 elements are left fr further search 12 Thus, after kth comparison, /2K elements are lft for further search Se swe ye [_——/-/-~-~-~—iico|° Outline of Presentation @ Multidimensional Arrays ae Program: Binary Search, Sllide - II return binarySearch(1ist, key, mid+, upper) _ a Program: Binary Search, Sllide - V 12 When k ~ logan, only one element is lft in the array, 1 Therefor, in the worst case, we need log +1 comparisons for finding a key in the sorted array, (@ For an array of 1024 (2!) elements: = Binay search requires 11 comparisons in the worst case f Linear search requires 1024 comparisons in the worst ease Multi-dimensional Array One-dimensional (LD) array models a linear collection of elements, To represent a table or matrix, we can use two-dimensional (2D) array 'A.2D array in Java is declared as an array of arrays of objects. Similar way, we can represent 2 3D array or multi-gimensional array SS Declaring a 2D Array a The syntax to declare a 2D array is as follows datatypelI() svraylemes 1 eating a 2D Array 1 Similar to 20 array, we use new operator to create the array with the following syntax ‘arraylane = nov datatype [rowSize] [columnSize); ‘2 We can combine declaration and creation in one statement Gavatype (I) arraylage = now @atatype arrayName [i 12 The following code declares 2 2D array of int data type Tipreterted style a Initializing 2D array © If an array is created using new operator, we can assign value to each clement by accessing an array element using the following syntax: datatype [rewSize] (ceolumnSize]; datatype arrayt! new datatype [rewSize] [columnsize] lowing code creates an array of type Tat GST a] Th Tet watrae Lengths of 2D Array 8 A.2D array is actually an stray in which each element is @ ‘one-dimensional array 8 A.2D atray of primitive type in Java can be represented as below: ifatrie GT = 5 {8 Java provides a shorthang notation to create an array abject and foal initialize it at the same time: , aio) | oror Toone [sora [tir Jatoieng=¢ \fiee 00) wapeix = Casa, soc [fy [ona [waar [war |otnsnemes sf tele lriap, a] fsitizisy'a, says) [nar [arr [on Jina ‘9 When we assign literals as values of atray elements, we do not need to use new operator. 18 We can see that 3 2D array is an array of 1D arrays. 1 In the aray, matrix, there are three rows and four colurens Representation of 2D Array of objects 19 A.20 array of objects is represented indifferent way. © The following shows an array of objects of size 2 X 4 on ot abat obcarreo) chiesrayohengh = 7 cbnctorndtl t+) cieasray length = [_——/-/-~-~-~—iico|° 12 The number of rows can be obtained using length property of array 3 and the number of columns ean be obtained using length property on 2 row (6, a[0] length gives length of row 9) Ragged Array 1 As each row in two-dimensional aray is itself an array, Each row can have eifferent length ‘@ Am array with ifferent lengths in each row is called ragged array or Bene orey ‘| “ast ig a877 foo ao) mea) 2) 28-307 e505 wn) Ls hb ar] SS Program: Matrix Addition, Slide - | Seanner [import java. weil [class Watrixaddicion( public static void main(str astO0 mi, may int Rows, ‘nColumns; 11 argsd¢ Scanner System. out. pr. nRows = input System. out pr: colunne pColuans = Anput=ney_ Scanner (System. in) Ene nextInt 0; Rove] [nColumns] = (nRews] [nColumns]; System. out -printin( e Matrix-L mi = new a a Program: Matrix Addition, Slide - III 0 450; i

You might also like