SlideShare a Scribd company logo
Introduction to Arrays
2
What are 1-D arrays?
 
 An array is an object that is used to store a list of values of the same type.
 It is made out of a contiguous block of memory that is divided into a number of "slots“ or varia
 Each slot can be accessed by using its index (or subscript).
 If there are N slots in an array, the indexes will be 0 through N-1.
 The diagram on the right shows a 5-element array. The indexes are from 0 to 4
 An array that uses a single subscript is called a one dimensional array.
 Two dimensional arrays, three dimensional arrays, and higher dimensional arrays also
exist:
3
1-D Array Declaration
 For any type T, T[ ] is a class, whose instances are arrays of type T.
 Thus, the following statement declares a reference variable, b, of type T array:
T[] b;
 For any positive integer n, the following expression creates a new T[ ] object of size n and
stores its reference in b:
b = new T[n] ;
 As usual, the two expressions can be combined together as:
T[] b = new T[n] ;
 For example, the following declares an int[] , grades, of size 10:
int[ ] grades = new int[10];
4
1-D Array Declaration (cont’d)
 The declaration of an array of size n creates n variables of the base type T.
 These variables are indexed starting from 0 to n-1. They are called subscripted variables.
 A subscripted variable can be used anywhere an ordinary variable of the same type can
be used.
 The slots of an array are initialized to the default value for their type.
 Each slot of a numeric array is initialized to zero.
 Each array object has a public instance variable, length, that stores the size of the array.
 Thus, the following statement prints 10, the size of grades:
System.out.println(grades.length);
 Once an array has been constructed, its length does not change.
 Other examples of 1D-array declaration are:
double[ ] price = new double[500]; // each element is initialized to 0.0
boolean[ ] flag = new boolean[20]; // each element is initialized to false
5
Accessing elements of a 1-D Array
 A particular variable is accessed by indexing the array reference with the index
(subscript) of the variable in square brackets:
grades[4] = 20;
 The following example, re-initializes each variable with twice its index:
int[] grades = new int[10];
for(int i = 0; i < grades.length; i++)
grades[i] = 2*i;
 The use of grades.length instead of 10 makes the code more general.
6
Accessing elements of a 1-D Array (cont'd )
 The following prints the values of the array re-initialized by the example in the previous
slide.
for(int i = 0; i < grades.length; i++)
System.out.print(grades[i] + “ “);
 Output:
0 2 4 6 8 10 14 16
18
 Note: Trying to access an element with an invalid index causes a run-time error:
ArrayIndexOutOfBoundsException:
int x = grades[10]; // causes run-time error
7
Accessing elements of a 1-D Array (cont'd )
 The indexes (subscripts) of an array must always be of integer type except long
(int, char, short, byte).
 An array index can be any expression that evaluates to an integer within the allowed
index range:
double[] val = new double[20]; int k = 3;
val[0] = 1.5;
val[1] = 10.0;
val[2] = 15.5;
val[k] = val[k-1] + val[k - 2]; // same as val[3] = val[2] + val[1]
val[ k*2 + 3 ] = 24 + val[13]; // same as: val[ 9 ] = 24 + 0.0
System.out.println( "val[" + k + "] == " + val[k] ); // output: val[3] = 25.5
Note: the following are invalid because the index is not of type int, char, short, or byte:
long k = 5L;
val[k] = 33.2;
val[8.0] = 75.5;
8
Using Subscripts with an Array
Enhanced for loop
» Cycle through array
» Without specifying starting and ending points for loop control variable
for(int val : scoreArray)
System.out.println(val);
9
Initializer List
 Initializer list can be used to instantiate and initialize an array in one step:
int[ ] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
char[ ] letterGrade = {’
A’
, ‘
B’
, ‘C’, ‘
D’
, ‘
F’
};
 It is actually the compiler that fills the gap. Thus, in the first example, the compiler
would
add the following:
int[] prime = new int[10];
prime[0] = 2; prime[1] = 3; ... prime[9] = 29;
 Observe that when an initializer list is used:
 The new operator is not required.
 The size is not required; it is computed by the compiler.
10
Copying one array to another
 Consider the following declarations:
int[ ] array1 = {22, 3, 50, 7, 11, 13, 17};
int[ ] array2 = {3, 5, 8, 20, 0, 100, 40};
 The assignment statement :
array1 = array2;
does not copy the contents of array2 to array1; it makes the reference array1 to refer
to the array object referenced by array2. The object that was referenced by array1
becomes garbage.
 To copy the contents of array2 to array1, code like the following is used:
for(int k = 0; k < array2.length; k++)
array1[k] = array2[k];
11
Array used as a Parameter
Remember that a parameter is data that is supplied to a method just before it starts
running.
The following method prints the content of an int array passed to it as parameter:
class MyArray {
public void print (int[] x) {
for(int i = 0; i < x.length; i++)
System.out.print(x[i]+ " ");
System.out.println();
}
}
The method is written using the parameter x to refer to the actual data that it will be
supplied with.
The method is written without referring to any particular data. When the print()
method is running it has a reference to an array object in its parameter x.
12
Example(1)
class ArrayDemo {
public static void main ( String[] args ) {
MyArray operate = new MyArray();
int[] ar1 = { -20, 19, 1, 5, -1, 27 } ;
System.out.print ("The array is: " );
operate.print( ar1 );
}
}
MyArray
print(x)
operate
-20
19
1
5
-1
27
ar1
public static void print (int[] x) {
for(int i = 0; i < x.length; i++)
System.out.print(a[x]+ " ");
System.out.println();
}
13
Parameter Connected to New Data
Could the main() method create a second array and use the print()
method with it?
Example (2): What is the output?
class ArrayDemo {
public static void main ( String[] args ) {
MyArray operate = new MyArray();
int[] ar1 = { -20, 19, 1, 5, -1, 27 } ;
int[] ar2 = {1, 2, 6, 3, 9, 5};
System.out.print("The array is: " );
operate.print( ar1 );
System.out.print("The second array is: " );
operate.print( ar2 );
}
}
The array is: -20 19 1 5 -1 27
The second array is: 1 2 6 3 9 5
14
Using Two-Dimensional and
Multidimensional Arrays
One-dimensional or single-dimensional array
» Picture as column of values
» Elements accessed using single subscript
Two-dimensional arrays
» Two or more columns of values
» Rows and columns
» Use two subscripts
» Matrix or table
int[][] someNumbers = new int[3][4];
15
View of a Two-Dimensional Array in Memory
16
Using Two-Dimensional and
Multidimensional Arrays (continued)
int[][] rents = { {400, 450, 510},
{500, 560, 630},
{625, 676, 740},
{1000, 1250, 1600} };
public static void displayScores(int[]
[]scoresArray)
17
Using Two-Dimensional and
Multidimensional Arrays (continued)
Multidimensional arrays
» More than two dimensions
Create arrays of any size
» Keep track of order of variables needed as subscripts
» Don’t exhaust computer’s memory

More Related Content

What's hot (20)

PPTX
Arrays In C++
Awais Alam
 
PPTX
ARRAY
ayush raj
 
PPSX
C Programming : Arrays
Gagan Deep
 
PPTX
Array
Anil Neupane
 
PPT
Multidimensional array in C
Smit Parikh
 
PPTX
Arrays in java language
Hareem Naz
 
PPTX
Arrays in c
Jeeva Nanthini
 
PPTX
C++ lecture 04
HNDE Labuduwa Galle
 
PPTX
2D Array
Ehatsham Riaz
 
PPTX
Array lecture
Joan Saño
 
PPTX
A Presentation About Array Manipulation(Insertion & Deletion in an array)
Imdadul Himu
 
PPT
C++ Arrays
أحمد محمد
 
PPTX
Arrays
Trupti Agrawal
 
PPTX
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
PPTX
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
PPT
Array Presentation
Deep Prajapati Microplacer
 
PPTX
Arrays C#
Raghuveer Guthikonda
 
PDF
Two dimensional array
Rajendran
 
PPT
Arrays Class presentation
Neveen Reda
 
PPT
Two dimensional array
Rajendran
 
Arrays In C++
Awais Alam
 
ARRAY
ayush raj
 
C Programming : Arrays
Gagan Deep
 
Multidimensional array in C
Smit Parikh
 
Arrays in java language
Hareem Naz
 
Arrays in c
Jeeva Nanthini
 
C++ lecture 04
HNDE Labuduwa Galle
 
2D Array
Ehatsham Riaz
 
Array lecture
Joan Saño
 
A Presentation About Array Manipulation(Insertion & Deletion in an array)
Imdadul Himu
 
C++ Arrays
أحمد محمد
 
Array Introduction One-dimensional array Multidimensional array
imtiazalijoono
 
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
Array Presentation
Deep Prajapati Microplacer
 
Two dimensional array
Rajendran
 
Arrays Class presentation
Neveen Reda
 
Two dimensional array
Rajendran
 

Similar to Data Structure Midterm Lesson Arrays (20)

PPT
Java: Introduction to Arrays
Tareq Hasan
 
PPTX
Arrays in programming
TaseerRao
 
PPT
ch06.ppt
AqeelAbbas94
 
PPT
ch06.ppt
ansariparveen06
 
PPT
array Details
shivas379526
 
PPT
ch06.ppt
chandrasekar529044
 
PDF
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
PPTX
Chapter 7.1
sotlsoc
 
DOCX
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
PPTX
6_Array.pptx
shafat6712
 
PDF
Arrays a detailed explanation and presentation
riazahamed37
 
PPT
Array
PRN USM
 
PPT
L10 array
teach4uin
 
PDF
Array
Ravi_Kant_Sahu
 
PDF
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
DOCX
Java R20 - UNIT-3.docx
Pamarthi Kumar
 
PDF
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
PPT
Eo gaddis java_chapter_07_5e
Gina Bullock
 
PPT
17-Arrays en java presentación documento
DiegoGamboaSafla
 
DOCX
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Java: Introduction to Arrays
Tareq Hasan
 
Arrays in programming
TaseerRao
 
ch06.ppt
AqeelAbbas94
 
ch06.ppt
ansariparveen06
 
array Details
shivas379526
 
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
Chapter 7.1
sotlsoc
 
Arraysnklkjjkknlnlknnjlnjljljkjnjkjn.docx
pranauvsps
 
6_Array.pptx
shafat6712
 
Arrays a detailed explanation and presentation
riazahamed37
 
Array
PRN USM
 
L10 array
teach4uin
 
Java chapter 6 - Arrays -syntax and use
Mukesh Tekwani
 
Java R20 - UNIT-3.docx
Pamarthi Kumar
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Eo gaddis java_chapter_07_5e
Gina Bullock
 
17-Arrays en java presentación documento
DiegoGamboaSafla
 
Class notes(week 4) on arrays and strings
Kuntal Bhowmick
 
Ad

More from Maulen Bale (9)

PPTX
Data Comm | Making Ethernet Cable
Maulen Bale
 
PPTX
STATISTICS | Measures Of Central Tendency
Maulen Bale
 
PPTX
Operating Systems & Applications
Maulen Bale
 
PDF
Systems Analysis Midterm Lesson
Maulen Bale
 
PDF
Trigonometry midterm
Maulen Bale
 
PPTX
COLLEGE ALGEBRA - MIDTERM
Maulen Bale
 
PPTX
Data Communication & Network
Maulen Bale
 
PDF
Data communication computer_network_tutorial
Maulen Bale
 
PPTX
Measures Of Central Tendency
Maulen Bale
 
Data Comm | Making Ethernet Cable
Maulen Bale
 
STATISTICS | Measures Of Central Tendency
Maulen Bale
 
Operating Systems & Applications
Maulen Bale
 
Systems Analysis Midterm Lesson
Maulen Bale
 
Trigonometry midterm
Maulen Bale
 
COLLEGE ALGEBRA - MIDTERM
Maulen Bale
 
Data Communication & Network
Maulen Bale
 
Data communication computer_network_tutorial
Maulen Bale
 
Measures Of Central Tendency
Maulen Bale
 
Ad

Recently uploaded (20)

PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
infertility, types,causes, impact, and management
Ritu480198
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
epi editorial commitee meeting presentation
MIPLM
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Controller Request and Response in Odoo18
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
Difference between write and update in odoo 18
Celine George
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 

Data Structure Midterm Lesson Arrays

  • 2. 2 What are 1-D arrays?    An array is an object that is used to store a list of values of the same type.  It is made out of a contiguous block of memory that is divided into a number of "slots“ or varia  Each slot can be accessed by using its index (or subscript).  If there are N slots in an array, the indexes will be 0 through N-1.  The diagram on the right shows a 5-element array. The indexes are from 0 to 4  An array that uses a single subscript is called a one dimensional array.  Two dimensional arrays, three dimensional arrays, and higher dimensional arrays also exist:
  • 3. 3 1-D Array Declaration  For any type T, T[ ] is a class, whose instances are arrays of type T.  Thus, the following statement declares a reference variable, b, of type T array: T[] b;  For any positive integer n, the following expression creates a new T[ ] object of size n and stores its reference in b: b = new T[n] ;  As usual, the two expressions can be combined together as: T[] b = new T[n] ;  For example, the following declares an int[] , grades, of size 10: int[ ] grades = new int[10];
  • 4. 4 1-D Array Declaration (cont’d)  The declaration of an array of size n creates n variables of the base type T.  These variables are indexed starting from 0 to n-1. They are called subscripted variables.  A subscripted variable can be used anywhere an ordinary variable of the same type can be used.  The slots of an array are initialized to the default value for their type.  Each slot of a numeric array is initialized to zero.  Each array object has a public instance variable, length, that stores the size of the array.  Thus, the following statement prints 10, the size of grades: System.out.println(grades.length);  Once an array has been constructed, its length does not change.  Other examples of 1D-array declaration are: double[ ] price = new double[500]; // each element is initialized to 0.0 boolean[ ] flag = new boolean[20]; // each element is initialized to false
  • 5. 5 Accessing elements of a 1-D Array  A particular variable is accessed by indexing the array reference with the index (subscript) of the variable in square brackets: grades[4] = 20;  The following example, re-initializes each variable with twice its index: int[] grades = new int[10]; for(int i = 0; i < grades.length; i++) grades[i] = 2*i;  The use of grades.length instead of 10 makes the code more general.
  • 6. 6 Accessing elements of a 1-D Array (cont'd )  The following prints the values of the array re-initialized by the example in the previous slide. for(int i = 0; i < grades.length; i++) System.out.print(grades[i] + “ “);  Output: 0 2 4 6 8 10 14 16 18  Note: Trying to access an element with an invalid index causes a run-time error: ArrayIndexOutOfBoundsException: int x = grades[10]; // causes run-time error
  • 7. 7 Accessing elements of a 1-D Array (cont'd )  The indexes (subscripts) of an array must always be of integer type except long (int, char, short, byte).  An array index can be any expression that evaluates to an integer within the allowed index range: double[] val = new double[20]; int k = 3; val[0] = 1.5; val[1] = 10.0; val[2] = 15.5; val[k] = val[k-1] + val[k - 2]; // same as val[3] = val[2] + val[1] val[ k*2 + 3 ] = 24 + val[13]; // same as: val[ 9 ] = 24 + 0.0 System.out.println( "val[" + k + "] == " + val[k] ); // output: val[3] = 25.5 Note: the following are invalid because the index is not of type int, char, short, or byte: long k = 5L; val[k] = 33.2; val[8.0] = 75.5;
  • 8. 8 Using Subscripts with an Array Enhanced for loop » Cycle through array » Without specifying starting and ending points for loop control variable for(int val : scoreArray) System.out.println(val);
  • 9. 9 Initializer List  Initializer list can be used to instantiate and initialize an array in one step: int[ ] prime = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; char[ ] letterGrade = {’ A’ , ‘ B’ , ‘C’, ‘ D’ , ‘ F’ };  It is actually the compiler that fills the gap. Thus, in the first example, the compiler would add the following: int[] prime = new int[10]; prime[0] = 2; prime[1] = 3; ... prime[9] = 29;  Observe that when an initializer list is used:  The new operator is not required.  The size is not required; it is computed by the compiler.
  • 10. 10 Copying one array to another  Consider the following declarations: int[ ] array1 = {22, 3, 50, 7, 11, 13, 17}; int[ ] array2 = {3, 5, 8, 20, 0, 100, 40};  The assignment statement : array1 = array2; does not copy the contents of array2 to array1; it makes the reference array1 to refer to the array object referenced by array2. The object that was referenced by array1 becomes garbage.  To copy the contents of array2 to array1, code like the following is used: for(int k = 0; k < array2.length; k++) array1[k] = array2[k];
  • 11. 11 Array used as a Parameter Remember that a parameter is data that is supplied to a method just before it starts running. The following method prints the content of an int array passed to it as parameter: class MyArray { public void print (int[] x) { for(int i = 0; i < x.length; i++) System.out.print(x[i]+ " "); System.out.println(); } } The method is written using the parameter x to refer to the actual data that it will be supplied with. The method is written without referring to any particular data. When the print() method is running it has a reference to an array object in its parameter x.
  • 12. 12 Example(1) class ArrayDemo { public static void main ( String[] args ) { MyArray operate = new MyArray(); int[] ar1 = { -20, 19, 1, 5, -1, 27 } ; System.out.print ("The array is: " ); operate.print( ar1 ); } } MyArray print(x) operate -20 19 1 5 -1 27 ar1 public static void print (int[] x) { for(int i = 0; i < x.length; i++) System.out.print(a[x]+ " "); System.out.println(); }
  • 13. 13 Parameter Connected to New Data Could the main() method create a second array and use the print() method with it? Example (2): What is the output? class ArrayDemo { public static void main ( String[] args ) { MyArray operate = new MyArray(); int[] ar1 = { -20, 19, 1, 5, -1, 27 } ; int[] ar2 = {1, 2, 6, 3, 9, 5}; System.out.print("The array is: " ); operate.print( ar1 ); System.out.print("The second array is: " ); operate.print( ar2 ); } } The array is: -20 19 1 5 -1 27 The second array is: 1 2 6 3 9 5
  • 14. 14 Using Two-Dimensional and Multidimensional Arrays One-dimensional or single-dimensional array » Picture as column of values » Elements accessed using single subscript Two-dimensional arrays » Two or more columns of values » Rows and columns » Use two subscripts » Matrix or table int[][] someNumbers = new int[3][4];
  • 15. 15 View of a Two-Dimensional Array in Memory
  • 16. 16 Using Two-Dimensional and Multidimensional Arrays (continued) int[][] rents = { {400, 450, 510}, {500, 560, 630}, {625, 676, 740}, {1000, 1250, 1600} }; public static void displayScores(int[] []scoresArray)
  • 17. 17 Using Two-Dimensional and Multidimensional Arrays (continued) Multidimensional arrays » More than two dimensions Create arrays of any size » Keep track of order of variables needed as subscripts » Don’t exhaust computer’s memory