SlideShare a Scribd company logo
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

What's hot

Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
Umar Farooq
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
Tareq Hasan
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
أحمد محمد
 
C programming assignment help
C programming assignment helpC programming assignment help
C programming assignment help
Hebrew Johnson
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
Muhammad Hammad Waseem
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1sotlsoc
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
Abdullah Al-hazmy
 
Array data structure
Array data structureArray data structure
Array data structure
maamir farooq
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
MLG College of Learning, Inc
 
7array in c#
7array in c#7array in c#
7array in c#
Sireesh K
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Fatima Kate Tanay
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Janpreet Singh
 

What's hot (19)

Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Array properties
Array propertiesArray properties
Array properties
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
C programming assignment help
C programming assignment helpC programming assignment help
C programming assignment help
 
Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
 
Array data structure
Array data structureArray data structure
Array data structure
 
Computer programming 2 Lesson 13
Computer programming 2  Lesson 13Computer programming 2  Lesson 13
Computer programming 2 Lesson 13
 
15 ruby arrays
15 ruby arrays15 ruby arrays
15 ruby arrays
 
7array in c#
7array in c#7array in c#
7array in c#
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 
LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 

Similar to Arrays in programming

Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
Pamarthi Kumar
 
Arrays
ArraysArrays
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
Prem Kumar Badri
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
Thesis Scientist Private Limited
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
Mohammed Khan
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
ajajkhan16
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6dplunkett
 
Arrays
ArraysArrays
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01Abdul Samee
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
berekethailu2
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
Muhammad Hammad Waseem
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
valerie5142000
 

Similar to Arrays in programming (20)

Java arrays (1)
Java arrays (1)Java arrays (1)
Java arrays (1)
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Java R20 - UNIT-3.docx
Java R20 - UNIT-3.docxJava R20 - UNIT-3.docx
Java R20 - UNIT-3.docx
 
Arrays
ArraysArrays
Arrays
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
Introduction to Arrays in C
Introduction to Arrays in CIntroduction to Arrays in C
Introduction to Arrays in C
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Array and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdfArray and its types and it's implemented programming Final.pdf
Array and its types and it's implemented programming Final.pdf
 
Ap Power Point Chpt6
Ap Power Point Chpt6Ap Power Point Chpt6
Ap Power Point Chpt6
 
Arrays
ArraysArrays
Arrays
 
Chap09
Chap09Chap09
Chap09
 
Arrays
ArraysArrays
Arrays
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
Ch08
Ch08Ch08
Ch08
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
Excellence Foundation for South Sudan
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Introduction to Quality Improvement Essentials
Introduction to Quality Improvement EssentialsIntroduction to Quality Improvement Essentials
Introduction to Quality Improvement Essentials
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 

Arrays in programming

  • 1.
  • 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