10 Array
10 Array
10.1 PROPERTIES
I nformationstorageisanimportanttaskforprogrammerstoperformintoday'stechnologicallyadvancedworld.
Forlateruse,eachandeveryitemofinformationmustbestoredinthememorylocation.Wealreadyknowwhat
avariableisandhowitstoresdata.Thesameway,dataisstoredusinganarray.However,Arraysareusedto
store multiple values in a single variable, instead of declaring separate variables for each value. It is adata
storagewherewestoreafixedsetofsimilarelements.Forexample,ifwewanttostorethenamesof40students
then we can create an array of the string type that can store 40 names.
D
● eclare the array name.
● Create the array.
● Initialize the array values.
Tocreateanarray,anarrayvariableofthedesireddatatypemustbedeclaredfirst.Thefollowingisthegeneral
f orm for declaring an array:
Here, the data type determines what type of elements will be stored in the array. For example:
int quiz_marks [ ] ;
I ntheabovedeclarationquiz_marksisthenameofthearray.Andthisarraywillstoreonlytheintegertypesof
elements. Althoughthisdeclarationestablishesthefactthatquiz_marksisanarrayvariable,noarrayactually
exists.
Tolinkquiz_markswithanactual,physicalarrayofintegers,wemustallocateoneactualarrayusingthe“new”
eyword and assign it to quiz_marks. “new “ is a special operator that allocates memory for arrays.
k
Now,wehavefinallycreatedtheactualarray.Here,5definesthelengthofthearray.Thatmeansthisarraycan
s tore five elements.
Page|56
his was the descriptive process for declaration and creation of an array. There is another short way for
T
declaring and creating an array. Instead of using two separate lines of codes wecansimplyuseonelinefor
declaration and creation of an array.
Here,wehavecreatedanintegerarray,whichcanstore5elements.Initiallywhenwecreateanintegerarray,all
the elements of the array remain 0.
Stackisatemporarymemory.afterusingnew,nowthearraywillbeinsertedintoanactualdatastoragememory
c alled heap. Also, the name of the array only refers to the address where the actual array is stored.
Initial elements of the array change according to the data type. According todifferentdatatypearrayinitial
e lements:
Object null
Array declaration and creation examples with different data types:
o sum up, there are two steps involved in constructing an array. First, you must create a variablewiththe
T
specifieddatatype.Second,youmustusethe“new”keywordtoallocatethememoryrequiredtostorethearray
andthenassignthatmemorytothearrayvariable.Afterthatdefaultelementswillbeassignedautomaticallyto
the array according to the data type.
Now,weneedtostoreouractualelements.Therearemultiplewaystoassignvaluesintoanemptyarray.The
eneral code for inserting any element into any specific index of an array is:
g
ere,atfirst,wedeclaredthearraywithlength4.Wedeclaredthedatatypeintegerthatiswhytheinitialarray
H
is loaded with all 0’s. After that we initiatedtheforloop,wherewestatedi=0.Becausethefirstindexofan
array is 0. Theloopwillstopwhenwereachthelastindexofthearray.Forthatreasonwehavetoknowthe
length of the array. In Java, the array length is the number of elements that an array can hold. There is no
predefined method to obtain the length of an array. We can find the array length in Javabyusingthearray
attribute length. We use this attribute with the array name. In the above example if we write:
[Link]([Link]);
ur program will give us 4 as an output. So, the last index of an array is [Link]-1.
O
In the above diagram, the value of “i” becomes: 0,1,2,3.
So,thefirstindexis0andthelastindexis3whichisthelength-1.Insidetheloopwearetakinginputsfrom
the user and inserting that input into the array index.
arr[i] = [Link]();
Inthisline,arristhenameofthearray,iistheindexnumber.[Link]()istakinginputsfromtheuser.Here,
extInt only takes the integer inputs
n
Page|59
Inthiswaywecantakeinputsfromtheuserandcreateanarray.Therearevariouswaystoinitializethearray
alues. Some of them are given below:
v
Created array:
aking User
T We can insert elements into an array by taking import [Link];
Input ser inputs.
u Scanner sc= new
a[i] = [Link](); Scanner([Link]);
In this line, a is the name of the array, i is the int a[] = new int [5];
index number. [Link]() is taking inputsfrom for (int i = 0; i < 5 ; i++) {
the user. Here, nextInt only takes the integer a[i] = [Link]();
inputs. }
andom value
R J avahasaspecialclasscalledRandom.Firstwe import [Link];
generator needtoimportthatclass.Afterthatwecreatean Random rd = new Random();
object of that class just like a scanner. int a[] = new int [5];
[Link](10). Here, rd is the object name, for (int i = 0; i < 5 ; i++) {
nextInt will generate only integervaluesand10 a[i] = [Link](10);
definestherange.Anyrandomnumbersbetween }
0 to 10 will be inserted into the array.
In this way, we can declare, create and initialize an array in java. For better efficiency practice different
a pproaches with different data types for array initialization.
comes the iteration part where we need to access the elements from thearray.Iteratingoveranarraymeans
a ccessing each element of the array one by one.
[Link](name[0]);
I ndex0containsthehighestscorer.Soinsidetheprintstatementifwewritethearraynamewithindex0.then
theoutputwillshowthehighestscorer'sname.Here,wejustprintedthename.Wecanalsostoreelementsas
separate variables from the array.
Here,wecreatedanewvariablecalledtop_scorerandcopiedanelementfromthearrayinsidethenewvariable.
he element will remain the same in the array, we just copied it and stored that copy inside a new variable.
T
e can iterate an array using not only for loop but also while loop and do while loops. As per our convenience
W
and requirements we can use any of the iteration processes.
or
F loop starts from 0, runsuntilitreachesthelastindexwhichis int a [ ] = {5,6,9,8,6};
Loop a rray length-1. i increments by 1. iterate over the whole array.
Page|61
inside the loop, print statement prints the elements. f or (int i = 0; i < [Link];
i++) {
[Link](a[i]);
}
hile
W loop starts from 0, runsuntilitreachesthelastindexwhichis int a [ ] = {5,6,9,8,6};
Loop a rray length-1. int i = 0;
inside the loop, print statement prints the elements and i while (i < [Link]) {
increments by 1. Iterate over the whole array. [Link](a[i]);
i++;
}
o
D heinitialvariableistartsfrom0.insidethedoblockwewrite
T int a [] = {5,6,9,8,6};
While thestatementstobeexecutedwhichisprintingelementsofthe int i = 0;
Loop array. Then we increment i by 1. Thenusingwhilewesetthe do {
value to stop the loop. [Link](a[i]);
i++;
} while (i < [Link]);
opying an
C reate another array with the same int arr2 [] = new int [[Link]];
C 5
5
array length and datatype, and copyallthe for (int i = 0; i < [Link]; i++){ 0
elements to the new array one by one. arr2[i]= arr[i]; 7
} -2
Thememoryaddressesofbotharrays for (int i = 0; i < [Link]; i++) { 9
are different and changing one array [Link](arr2[i]);
does not affect the another. }
10.5 MU
LTIDIMENSIONAL ARRAYS
he arrays we have looked at so far were all one-dimensional arrays (values are only in a row). When we want
T
to represent data in a tabular form (rows and columns), we use multidimensional arrays. These are basically
arrays of arrays, i.e. an array inside another array. The basic format for creating such arrays is-
For example:
oaccessormodifyvaluesofamultidimensionalarray,wecanusearrayindexing,justlikepreviousexamples,
T
but instead ofjustoneindex,weusemultipleindexestopointtothelocationofacertainvalue.Forexample
numbers[1][2]represents7, as [1] means the indexof the outer array, and [2] is the index of the inner array.
10.6 WO
RKSHEET
B. Given an array of integers, write a program to find the maximum element in the array.
iven Array 1
G
{5, 2, 8, 3, 9}
Sample Output 2
9
C. Write a function that takes an array of integers as input and returns the sum of all the elements.
iven Array 1
G
{5, 2, 8, 3, 9}
Sample Output 1
27
D. W rite a program that takes an array and a target element as input and printstheindexofthetarget
element in the array. If not found in the array, print “Not Found”.
iven Array 1
G
{5, 2, 8, 3, 9}
8
Sample Output 1
Target element is at index: 2
iven Array 2
G
{5, 2, 8, 3, 9}
18
Sample Output 2
Not Found
E. Given an array of integers, write a program that prints the occurrence of each element in the array.
iven Array 1
G
{5, 3, 5}
Sample Output 1
5 is repeated 2 time(s)
3 is repeated 1 time(s)
Page|64
F. Given two arrays, write a program that prints an array containing the common elements in both arrays.
iven Arrays
G
{5, 2, 8, 3, 9}
{6, 3, 5, 11, 10}
Sample Output 1
{3, 5}
G. G ivenanarraywithduplicateelements,writeaprogramthatremovestheduplicatesandprintsanew
array with unique elements only.
iven Array 1
G
{5, 2, 8, 3, 2}
Sample Output 1
{5, 2, 8, 3}
H. Write a program that takes an array as input and returns a new array with the elements reversed.
iven Array 1
G
{1, 2, 3, 4, 5}
Sample Output 1
{5, 4, 3, 2, 1}