SlideShare a Scribd company logo
Arrays in programming
Object Oriented Programming (OOP)
Introduction to Arrays
Review
 A Conditionally-Controlled Loop repeats…
 as long as a particular condition exists.
 A Count-Controlled Loop repeats…
 a specific number of times.
 A count-controlled loop has three elements
 An initialization expression
 A test expression
 An update expression
 The difference between the prefix and postfix
increment operators is…
 pretest increments before the value of the operand is
evaluated, posttest increments after the value of the
operand is evaluated.
Review
 A Sentinel Value is…
 a special value that cannot be mistaken for normal input
that signals that a loop should terminate.
 break in a loop…
 makes the program’s control flow go to the statement
following the loop.
 continue in a loop…
 skips to the next iteration of the loop.
 Java provides a class that generates pseudo-random
numbers called…
 Random
Arrays
 So far we have worked primarily with primitive
variables
 One characteristic of primitive variables is that they hold
one value at a time.
 int x = 100 – can only hold one integer value at a time
(100 at this time)
 Imagine that you want to hold the names of 100
people at a time.
 What would you have to do?
 Declare 100 variables, one for each name.
 Better solution: Use Arrays.
 Arrays are complex variables that can hold multiple values of
the same data type.
 Now we can declare a single array that holds all the names.
 In Java, Arrays are objects and behave very similarly
(use new keyword to create the object, has methods,
etc.)
There are two types of array:
 Single Dimensional Array (1D Array)
One-dimensional array(1-D): It is a single array that holds multiple
values of the same type.
 Multidimensional Array (nth-D Array)
In such case, data is stored in row and column based index (matrix form).
Types of Arrays
One-Dimensional Array (1D)
 To declare an integer array:
int[] numbers;
 It is just like declaring any primitive variable, EXCEPT for the[]
between the data type and the identifier.
 Just like any other object, this does not create the array, it
creates a reference variable that can point to an array.
 To create an array object for this reference variable:
numbers = new int[6];
 The number inside of the square brackets is called the array’s
size declarator.
 An array’s Size Declarator indicates the number of elements, or
values the array can hold.
 Individual values inside of an array are called elements.
 So the numbers array can hold 6 integers.
 You can declare and create on the same line like any other
object:
int[] numbers = new int [6];
 The elements in an array are numbered starting
from 0.
 So the first element has index 0.
 The size declarator must be a non-negative
integer expression.
 Often cases we know the size of the array when
writing the code and can just use a literal.
 However, it is common practice to use a constant as the
size declarator.
final int NUM_ELEMENTS = 6;
double[] numbers = new double [NUM_ELEMENTS];
 Once an array is created the size cannot change!
One-Dimensional Array (1D)
Accessing Array Elements
 Even though, the array has one name, we can access
the individual elements by their index (or subscript).
 An element’s Index (or Subscript) is a uniquely
identifying number that is used to pinpoint its position in
the array.
 So, if I want a specific element, I use its index.
 Again, indices start at 0.
 When you access an element in the array, you can
use it just like any simple variable of the array’s
declared type.
 The following statement assigns 20 to the first
element in the numbers array:
numbers[0] = 20;
 To access an element of an array, simply use the
array name followed by the element’s index inside of
square brackets.
Array Example 1
 New Topics:
 Arrays
class ArrayExample {
public static void main(String[] args) {
int[] age = new int[5];
System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);
System.out.println(age[3]);
System.out.println(age[4]);
}
}
Array Example 2
 This seems repetitive…
 I have to use a separate segment of code for taking
in the employees hours and for printing the result
out.
 Is there a better way?
 Answer: Yes, using loops.
 Arrays work great with loops, because you can
loop through the elements of the array and
perform operations on them.
Bounds Checking and Off-by-One
Errors
 What is the problem with this?
int[] numbers = new int [3];
numbers[5] = 10;
 Answer: The index 5 is out of the bounds defined by the size
declarator.
 Java performs bounds checking at runtime.
 In the case with Java that means that if you attempt to index an
element outside of the array’s bounds, it will throw an exception
(cause an error and terminate your program).
 We will not discuss exceptions in this course.
 What is the problem with this?
int[] numbers = new int [3];
numbers[3] = 10;
 Answer: The index 3 is still out of the array’s bounds.
 Because indexing starts at 0, the last element of the array is the
size of the array minus 1.
 This is called an Off-by-One error.
Array Declaration Notes
 You can initialize Arrays just like any other variables.
int[] numbers = {1, 2, 3, 4, 5};
 This array has an implicit size of 5 and the values in the initialization are
indexed from left to right.
 Example: ArrayInitialization.java
 Java also allows for two different syntactical forms for declaring an
array:
int[] numbers;
int numbers[];
 The difference is when you declare multiple arrays on the same
line:
int[] numbers1, numbers2, numbers3;
 This declares three reference variables to integer arrays
int numbers1[], numbers2, numbers3;
 This declares one reference variable to an integer array and two primitive
integer variables
int numbers1[], numbers2[], numbers3[];
 This, again, declares three reference variables to integer arrays
Array Elements
 Individual array elements can be treated like any simple
variable of that type.
int[] numbers = new int[5];
int x = 5;
numbers[1] = x + 5;
x = numbers[1] + 20;
numbers[2] = numbers[1] / 5;
numbers[2]++;
 Also, since arrays are objects in Java, they have methods
and data members.
 For instance the length data member holds the number of
elements in the array.
 int size = numbers.length;
 This is helpful for looping through an array.
Enhanced for Loop
 The last kind of loop we will be discussing in this
course is called the enhanced for loop.
 The Enhanced for Loop is a special loop that iterates
through the elements in a collection (in this case array)
and allows access to each element.
 Each iteration of the loop corresponds to an element in
the array.
 General Form:
for(dataType elementVariable : array)
block or statement
 dataType – The type of the array
 elementVariable – A variable that holds the value of
the current iteration’s element.
 array – The array in which we are iterating through.
Enhanced for Loop Example
 Enhanced for Loop
class EnhancedForLoop {
public static void main(String[] args)
{
int primes[] = { 2, 3, 5, 7, 11, 13,
17, 19, 23, 29};
for (int t: primes) {
System.out.println(t);
}
}
}
Output:
2
3
5
7
11
13
17
19
23
29
When NOT To Use the Enhanced
for Loop
 The enhanced for loop is useful for when you
need only all the values of the array, but there are
many situations when you should NOT use it:
1. If you need to change the contents of an array
element
2. If you need to work through the array elements in
reverse order
3. If you need to access some of the array elements,
but not all of them
4. If you need to simultaneously work with two or
more arrays within the loop
5. If you need to refer to the index of a particular
element
 If any of these cases apply, use a regular for
loop.
Allowing the User to Specify an
Array’s Size
 Since the size declarator is an integer, you can let
the user enter an integer, and then create an
array of that size.
Reassigning Reference Variables
and Array Copying
 As stated before, you cannot change the size of an
array once it has been set.
 You can, however, make the reference variable point to
a new array.
int[] numbers = {1, 2, 3, 4, 5};
numbers = new int [10];
 What is the problem with this?
 Now numbers has no values in it!
 What you need to do is copy the elements of the old
array to the new one, and make the original reference
variable point to the new array:
1. Create a new reference variable
2. Make the new reference variable point to an array of the
newly specified size
3. Use a loop to assign the elements from the old array to the
new one.
4. Assign the new reference variable to the old one.
Array Copying Example
 Array Copying
public class ArrayCopying{
public static void main(String[] args) {
int a[] = {1, 8, 3};
// Create an array b[] of same size as a[]
int b[] = new int[a.length];
// Copy elements of a[] to b[]
for (int i=0; i<a.length; i++)
b[i] = a[i];
// Change b[] to verify that b[] is different
// from a[]
b[0]++;
System.out.println("Contents of a[] ");
for (int i=0; i<a.length; i++)
System.out.print(a[i] + " ");
System.out.println("nnContents of b[] ");
for (int i=0; i<b.length; i++)
System.out.print(b[i] + " ");
}
}
Output:
Contents of a[]
1 8 3
Contents of b[]
2 8 3
Two-Dimensional Array (2D)
 Syntax to Declare 2D Array in Java :
dataType[ ][ ] arr ; (or)
dataType
dataType
dataType
[ ][ ]arr ; (or)
arr[ ][ ]; (or)
[ ]arr[ ];
Example to instantiate Multidimensional Array inJava:
int[ ][ ] arr=new int[3][3]; //3 row and 3 column
Example to initialize Multidimensional Array in Java:
arr[0][0]=1; arr[0][1]=2; arr[0][2]=3;
arr[1][0]=4; arr[1][1]=5; arr[1][2]=6;
arr[2][0]=7; arr[2][1]=8; arr[2][2]=9;
Example
class GFG {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Output:
1 2
3 4
Any Question…???

More Related Content

PPT
9781439035665 ppt ch09
PPT
Array
PPT
2 arrays
PPTX
Arrays in Data Structure and Algorithm
PPT
Arrays
PPTX
C# Arrays
PPTX
Data structures in c#
PPT
07 Arrays
9781439035665 ppt ch09
Array
2 arrays
Arrays in Data Structure and Algorithm
Arrays
C# Arrays
Data structures in c#
07 Arrays

What's hot (19)

PPT
Strings Arrays
PPTX
Data Structures in Python
PDF
Array and Collections in c#
PPTX
PPT
Java: Introduction to Arrays
DOC
Array properties
PPT
C++ Arrays
PDF
C programming assignment help
PPTX
Data Structures - Lecture 3 [Arrays]
PPTX
Chapter 7.1
PPT
Data Structures- Part3 arrays and searching algorithms
PDF
Array data structure
PPTX
Computer programming 2 Lesson 13
PDF
15 ruby arrays
PPTX
7array in c#
PDF
An Introduction to Programming in Java: Arrays
PDF
LectureNotes-05-DSA
PPTX
Passing an Array to a Function (ICT Programming)
PPT
Arrays in C++
Strings Arrays
Data Structures in Python
Array and Collections in c#
Java: Introduction to Arrays
Array properties
C++ Arrays
C programming assignment help
Data Structures - Lecture 3 [Arrays]
Chapter 7.1
Data Structures- Part3 arrays and searching algorithms
Array data structure
Computer programming 2 Lesson 13
15 ruby arrays
7array in c#
An Introduction to Programming in Java: Arrays
LectureNotes-05-DSA
Passing an Array to a Function (ICT Programming)
Arrays in C++
Ad

Similar to Arrays in programming (20)

PDF
Java arrays (1)
PDF
Homework Assignment – Array Technical DocumentWrite a technical .pdf
DOCX
Java R20 - UNIT-3.docx
PPTX
Module 7 : Arrays
PPTX
Unit4pptx__2024_11_ 11_10_16_09.pptx
PDF
Introduction to Arrays in C
PPTX
Lecture 7
PDF
Array and its types and it's implemented programming Final.pdf
PPT
Ap Power Point Chpt6
PDF
PPT
Chap09
PPTX
Programming in c Arrays
PPTX
C++ - UNIT_-_IV.pptx which contains details about Pointers
PPT
Arrays Basicfundamentaldatastructure.ppt
PPTX
object oriented programing in python and pip
PPTX
arrays-120712074248-phpapp01
PPTX
Array In C++ programming object oriented programming
Java arrays (1)
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Java R20 - UNIT-3.docx
Module 7 : Arrays
Unit4pptx__2024_11_ 11_10_16_09.pptx
Introduction to Arrays in C
Lecture 7
Array and its types and it's implemented programming Final.pdf
Ap Power Point Chpt6
Chap09
Programming in c Arrays
C++ - UNIT_-_IV.pptx which contains details about Pointers
Arrays Basicfundamentaldatastructure.ppt
object oriented programing in python and pip
arrays-120712074248-phpapp01
Array In C++ programming object oriented programming
Ad

Recently uploaded (20)

PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Institutional Correction lecture only . . .
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Insiders guide to clinical Medicine.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
Complications of Minimal Access Surgery at WLH
PDF
Classroom Observation Tools for Teachers
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
master seminar digital applications in india
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Supply Chain Operations Speaking Notes -ICLT Program
Microbial diseases, their pathogenesis and prophylaxis
Institutional Correction lecture only . . .
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
TR - Agricultural Crops Production NC III.pdf
Sports Quiz easy sports quiz sports quiz
Microbial disease of the cardiovascular and lymphatic systems
Insiders guide to clinical Medicine.pdf
Computing-Curriculum for Schools in Ghana
FourierSeries-QuestionsWithAnswers(Part-A).pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Pharma ospi slides which help in ospi learning
Complications of Minimal Access Surgery at WLH
Classroom Observation Tools for Teachers
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
master seminar digital applications in india
GDM (1) (1).pptx small presentation for students
Anesthesia in Laparoscopic Surgery in India
Supply Chain Operations Speaking Notes -ICLT Program

Arrays in programming

  • 2. Object Oriented Programming (OOP) Introduction to Arrays
  • 3. Review  A Conditionally-Controlled Loop repeats…  as long as a particular condition exists.  A Count-Controlled Loop repeats…  a specific number of times.  A count-controlled loop has three elements  An initialization expression  A test expression  An update expression  The difference between the prefix and postfix increment operators is…  pretest increments before the value of the operand is evaluated, posttest increments after the value of the operand is evaluated.
  • 4. Review  A Sentinel Value is…  a special value that cannot be mistaken for normal input that signals that a loop should terminate.  break in a loop…  makes the program’s control flow go to the statement following the loop.  continue in a loop…  skips to the next iteration of the loop.  Java provides a class that generates pseudo-random numbers called…  Random
  • 5. Arrays  So far we have worked primarily with primitive variables  One characteristic of primitive variables is that they hold one value at a time.  int x = 100 – can only hold one integer value at a time (100 at this time)  Imagine that you want to hold the names of 100 people at a time.  What would you have to do?  Declare 100 variables, one for each name.  Better solution: Use Arrays.  Arrays are complex variables that can hold multiple values of the same data type.  Now we can declare a single array that holds all the names.  In Java, Arrays are objects and behave very similarly (use new keyword to create the object, has methods, etc.)
  • 6. There are two types of array:  Single Dimensional Array (1D Array) One-dimensional array(1-D): It is a single array that holds multiple values of the same type.  Multidimensional Array (nth-D Array) In such case, data is stored in row and column based index (matrix form). Types of Arrays
  • 7. One-Dimensional Array (1D)  To declare an integer array: int[] numbers;  It is just like declaring any primitive variable, EXCEPT for the[] between the data type and the identifier.  Just like any other object, this does not create the array, it creates a reference variable that can point to an array.  To create an array object for this reference variable: numbers = new int[6];  The number inside of the square brackets is called the array’s size declarator.  An array’s Size Declarator indicates the number of elements, or values the array can hold.  Individual values inside of an array are called elements.  So the numbers array can hold 6 integers.  You can declare and create on the same line like any other object: int[] numbers = new int [6];
  • 8.  The elements in an array are numbered starting from 0.  So the first element has index 0.  The size declarator must be a non-negative integer expression.  Often cases we know the size of the array when writing the code and can just use a literal.  However, it is common practice to use a constant as the size declarator. final int NUM_ELEMENTS = 6; double[] numbers = new double [NUM_ELEMENTS];  Once an array is created the size cannot change! One-Dimensional Array (1D)
  • 9. Accessing Array Elements  Even though, the array has one name, we can access the individual elements by their index (or subscript).  An element’s Index (or Subscript) is a uniquely identifying number that is used to pinpoint its position in the array.  So, if I want a specific element, I use its index.  Again, indices start at 0.  When you access an element in the array, you can use it just like any simple variable of the array’s declared type.  The following statement assigns 20 to the first element in the numbers array: numbers[0] = 20;  To access an element of an array, simply use the array name followed by the element’s index inside of square brackets.
  • 10. Array Example 1  New Topics:  Arrays class ArrayExample { public static void main(String[] args) { int[] age = new int[5]; System.out.println(age[0]); System.out.println(age[1]); System.out.println(age[2]); System.out.println(age[3]); System.out.println(age[4]); } }
  • 11. Array Example 2  This seems repetitive…  I have to use a separate segment of code for taking in the employees hours and for printing the result out.  Is there a better way?  Answer: Yes, using loops.  Arrays work great with loops, because you can loop through the elements of the array and perform operations on them.
  • 12. Bounds Checking and Off-by-One Errors  What is the problem with this? int[] numbers = new int [3]; numbers[5] = 10;  Answer: The index 5 is out of the bounds defined by the size declarator.  Java performs bounds checking at runtime.  In the case with Java that means that if you attempt to index an element outside of the array’s bounds, it will throw an exception (cause an error and terminate your program).  We will not discuss exceptions in this course.  What is the problem with this? int[] numbers = new int [3]; numbers[3] = 10;  Answer: The index 3 is still out of the array’s bounds.  Because indexing starts at 0, the last element of the array is the size of the array minus 1.  This is called an Off-by-One error.
  • 13. Array Declaration Notes  You can initialize Arrays just like any other variables. int[] numbers = {1, 2, 3, 4, 5};  This array has an implicit size of 5 and the values in the initialization are indexed from left to right.  Example: ArrayInitialization.java  Java also allows for two different syntactical forms for declaring an array: int[] numbers; int numbers[];  The difference is when you declare multiple arrays on the same line: int[] numbers1, numbers2, numbers3;  This declares three reference variables to integer arrays int numbers1[], numbers2, numbers3;  This declares one reference variable to an integer array and two primitive integer variables int numbers1[], numbers2[], numbers3[];  This, again, declares three reference variables to integer arrays
  • 14. Array Elements  Individual array elements can be treated like any simple variable of that type. int[] numbers = new int[5]; int x = 5; numbers[1] = x + 5; x = numbers[1] + 20; numbers[2] = numbers[1] / 5; numbers[2]++;  Also, since arrays are objects in Java, they have methods and data members.  For instance the length data member holds the number of elements in the array.  int size = numbers.length;  This is helpful for looping through an array.
  • 15. Enhanced for Loop  The last kind of loop we will be discussing in this course is called the enhanced for loop.  The Enhanced for Loop is a special loop that iterates through the elements in a collection (in this case array) and allows access to each element.  Each iteration of the loop corresponds to an element in the array.  General Form: for(dataType elementVariable : array) block or statement  dataType – The type of the array  elementVariable – A variable that holds the value of the current iteration’s element.  array – The array in which we are iterating through.
  • 16. Enhanced for Loop Example  Enhanced for Loop class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; for (int t: primes) { System.out.println(t); } } } Output: 2 3 5 7 11 13 17 19 23 29
  • 17. When NOT To Use the Enhanced for Loop  The enhanced for loop is useful for when you need only all the values of the array, but there are many situations when you should NOT use it: 1. If you need to change the contents of an array element 2. If you need to work through the array elements in reverse order 3. If you need to access some of the array elements, but not all of them 4. If you need to simultaneously work with two or more arrays within the loop 5. If you need to refer to the index of a particular element  If any of these cases apply, use a regular for loop.
  • 18. Allowing the User to Specify an Array’s Size  Since the size declarator is an integer, you can let the user enter an integer, and then create an array of that size.
  • 19. Reassigning Reference Variables and Array Copying  As stated before, you cannot change the size of an array once it has been set.  You can, however, make the reference variable point to a new array. int[] numbers = {1, 2, 3, 4, 5}; numbers = new int [10];  What is the problem with this?  Now numbers has no values in it!  What you need to do is copy the elements of the old array to the new one, and make the original reference variable point to the new array: 1. Create a new reference variable 2. Make the new reference variable point to an array of the newly specified size 3. Use a loop to assign the elements from the old array to the new one. 4. Assign the new reference variable to the old one.
  • 20. Array Copying Example  Array Copying public class ArrayCopying{ public static void main(String[] args) { int a[] = {1, 8, 3}; // Create an array b[] of same size as a[] int b[] = new int[a.length]; // Copy elements of a[] to b[] for (int i=0; i<a.length; i++) b[i] = a[i]; // Change b[] to verify that b[] is different // from a[] b[0]++; System.out.println("Contents of a[] "); for (int i=0; i<a.length; i++) System.out.print(a[i] + " "); System.out.println("nnContents of b[] "); for (int i=0; i<b.length; i++) System.out.print(b[i] + " "); } } Output: Contents of a[] 1 8 3 Contents of b[] 2 8 3
  • 21. Two-Dimensional Array (2D)  Syntax to Declare 2D Array in Java : dataType[ ][ ] arr ; (or) dataType dataType dataType [ ][ ]arr ; (or) arr[ ][ ]; (or) [ ]arr[ ]; Example to instantiate Multidimensional Array inJava: int[ ][ ] arr=new int[3][3]; //3 row and 3 column Example to initialize Multidimensional Array in Java: arr[0][0]=1; arr[0][1]=2; arr[0][2]=3; arr[1][0]=4; arr[1][1]=5; arr[1][2]=6; arr[2][0]=7; arr[2][1]=8; arr[2][2]=9;
  • 22. Example class GFG { public static void main(String[] args) { int[][] arr = { { 1, 2 }, { 3, 4 } }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } } Output: 1 2 3 4