4.4 Array 2022 2023 (Final)
4.4 Array 2022 2023 (Final)
0
JAVA LANGUAGE
COMPUTER SCIENCE
SC015
4.4 ARRAY
Learning Outcome
At the end of lesson, students should be able to :
height 1.4 2.0 0.7 1.9 1.5 1.0 Hold decimal value
elementType
- int arrayRefVar
- float []
- double - Indicate for array - Any valid variable name
- char declaration
- boolean
DECLARE AND CREATE ARRAY
DECLARING AN ARRAY
Examples :
int[] array1; // an array of int elements
double[] temp; // an array of double elements
char[] gender; // an array of char elements
boolean[] answer; // an array of boolean elements
DECLARE AND CREATE ARRAY
CREATING AN ARRAY
• Indicates how many positions the array should hold
(size of array)
int[] array1;
int[] array1 = new int[10];
array1 = new int[10];
Checkpoint 1
1. Define array.
___________________________________
___________________________________
2. Determine component the following declaration
statement.
double[] finalMark;
________________________ __________
___________________________________
Checkpoint 1
3. Write a Java code segment to perform the
following tasks :
Declare an array named pHvalue of type
double.
_____________________________________________
4. Declare and create array named marks to store
100 students’ marks.
_____________________________________________
4.4 ARRAY
At the end of lesson, students should be able to :
ARRAY INDEX
• The array elements are accessed through the index.
ARRAY INDEX
temp[0] = 33.3;
temp[1] = 31.5;
1 temp[2] = 29.0;
temp[3] = 30.2;
temp[4] = 38.7;
ACCESSING ARRAY
INITIALIZING ARRAY ELEMENTS
• Use the following shorthand:
temp[0] = sc.nextDouble();
1 temp[1] = sc.nextDouble();
temp[2] = sc.nextDouble();
temp[3] = sc.nextDouble();
temp[4] = sc.nextDouble();
ACCESSING ARRAY
INPUT ARRAY ELEMENTS
• Frequently, arrays are processed within for loops.
• We can write a repetition code (using for or while) to read
values into an array.
• Object name “.length” will store size of an array
Scanner sc = new Scanner(System.in);
double[] temp = new double[7];
2 for (int i = 0;i < temp.length;i = i + 1) // using for loop
{
temp[i] = sc.nextDouble();
}
ACCESSING ARRAY
INPUT ARRAY ELEMENTS
System.out.print(age[0]);
System.out.print(age[1]);
System.out.print(age[2]);
int [] age = {12, 4, 5, 2, 5};
System.out.print(age[3]); int i = 0;
while ( i < age.length)
System.out.print(age[4]);
{
System.out.print(age[i]);
i = i +1;
}
Checkpoint 2
1. Consider the following array.
double [ ] pressure = new double [10];
i. State the value of pressure.length
_________________________________
}
}
Linear Search in Array
- Do in practical session -