Arrays
Arrays
Arrays
Examples:
• Arrays
• Linked Lists
• Stacks, Queues
Grades 65 32 76 91 55 86
• Example:
float Grades[] = new float[7];
• During array declaration we may also put the brackets before the variable name:
i.e. float [ ]Grades = new float[7];
Programming and Data Structures 4
Initialising Arrays
• Arrays may be initialised in the following ways:
- int n[] = { 2, 4, 6, 8, 10 };
creates and initialises a five element array with specified values
• Note : if data type is a non primitive type then above expression would
create and initialise a 10 element array of nulls
• Array elements are indexed between zero and the size of the array minus one
• You can check the size of your array by calling the length member variable.
• e.g.
int results = new int[20];
:
printResults(results);
• Note :
- Arrays in Java are treated like objects thus all arrays are passed in by reference.
- We don’t need to pass in the array size since we can get this from the length method.
Pseudo-Code : Get_Average(Array[])
Begin
index = 0;
sum = 0;
for index = 0 to index = ArraySize -1
{
sum = sum + Array[index];
}
average = sum / ArraySize;
End
Programming and Data Structures 8
Sample Java Code for example
/*
* function which calculates and returns the average overall grade
*/
float Get_Average(float Grades[]);
{
float sum = 0; // initialise the sum variable
1 3 12 1 3 12 1 3
2 7 2 7 2 7
3 9 3 9 3 9
4 13 4 4 12
5 22 5 13 5 13
6 6 22 6 22
3. Replace the current element that we are on with the element before it.
Begin
for index = ArraySize-1 to index = position+1
{
List[index] = List[index-1];
}
List[position] = element;
End
• If we were to print out the values of these arrays by row we would get :
• Note : If there are not initialisers for a given row, primitive types are
initialised to zero and non primitive types are initialised to null.
• e.g.
void warp(int space[][][]);