Array with Looping
1
What is an array???
• An Array is A “Data Structure”
• An Array consists of data items of the same type, all with the same
name.
• The size of an Array is “static”.
• Once you have created an “array”, you cannot change the number of
elements it holds.
In Java, an array is a group of contiguous memory locations that all
have the same name and same type.
2
Creating Arrays
• An array is an object so it needs an object reference.
// Declare a reference to an array that will hold integers.
int[] numbers;
• The next step creates the array and assigns its
address to the numbers variable.
// Create a new array that will hold 6 integers.
numbers = new int[6];
0 0 0 0 0 0
index 0 index 1 index 2 index 3 index 4 index 5
Array element values are initialized to 0.
Array indexes always start at 0.
7-3
Alternate Array
Declaration
• Previously we showed arrays being declared:
int[] numbers;
– However, the brackets can also go here:
int numbers[];
– These are equivalent but the first style is typical.
7-4
Creating Arrays
• It is possible to declare an array
reference and create it in the same
statement.
int[] numbers = new int[6];
• Arrays may be of any type.
float[] temperatures = new float[100];
char[] letters = new char[41];
long[] units = new long[50];
double[] sizes = new double[1200];
7-5
How to initialize an array?
You can use an “Initializer List” enclosed in
braces to quickly insert values in your array:
int n[] = { 12, 44, 98, 1, 28 };
• Because this list has 5 values in it, the
resulting array will have 5 elements.
6
ARRAY
An array is a random-access storage
structure: Any element can be accessed
immediately from its index.
7
An Array is A “Data Structure”
x[0] 28
x[1] 44
x[2] 98
“28” is the first
element, with a x[3] 1
subscript of “0” x[4] 28
x[5] 5
x[6] 2
x[7] 29
x[8] 73
8
An Array is A “Data Structure”
• To learn the number of elements in the
array, you call a property called “length.”
For example:
int y = 0;
int[] x;
x = new int[5];
y = x.length;
• Notice, “length” is NOT a method, it is
a property. 9
Inputting and Outputting
Array Elements
• Array elements can be treated as any other variable.
• They are simply accessed by the same name and a subscript.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int list[] = new int[3];
int i;
for(i = 0; i < 3; ++i){
System.out.println("Enter a number");
list[i] = in.nextInt();
}
for(i = 0; i < 3; ++i)
System.out.println(list[i]);
7-10 }
String Arrays
• If an initialization list is not provided, the new
keyword must be used to create the array:
String[] names = new String[4];
The names variable holds
the address to the array.
Address
names[0] null
names[1] null
names[2] null
names[3] null
7-11
Do while loop
12
While loop
13