Arrays, Recursion
Arrays, Recursion
in
JAVA
TOPICS TO COVER:--
Array declaration and use.
One-Dimensional Arrays.
Passing arrays and array elements as parameters
Arrays of objects
Searching an array
Sorting elements in an array
ARRAYS
An array is group of like-typed variables that are referred to
by a common name.
scores 50.5
50 12.8
12 4.05
45 78
7.8 66
0.66100
1.00125
12.5
An array of size N is indexed from zero to N-1
INTEGER
FLOAT
An array can be of any type.
Specific element in an array is accessed by its index.
Can have more than one dimension
2D Array Elements
Row
Requires two indices
Which cell is
CHART [3][2]?
Column
scores[2]
0 1 2 3 4 5 6
50 12 45 78 66 100 125
5
DECLARAING ARRAYS
The general form of 1-d array declaration is:-
type var_name[ ]; 1. Even though an array variable
“scores” is declared, but there
int, float, char array name is no array actually existing.
2. “score” is set to NULL, i.e.
E.g.:--- int scores [ ]; an array with NO VALUE.
scores
int[] scores = new int[10];
NULL
boolean[] flags;
8
ARRAY INITIALIZATION
Giving values into the array created is known as
INITIALIZATION.
The values are delimited by braces and separated by commas
Examples:
int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
char[ ] letterGrades = {'A', 'B', 'C', 'D', ’F'};
Note that when an initializer list is used:
Example:- System.out.println(units[4]);
0 1 2 3 4 5 6 7 8 9
int[ ] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
PROCESSING ARRAY ELEMENTS
Often a for( ) loop is used to process each of the elements
of the array in turn.
0 1 2 3 4 5 6
score
50 12 45 78 66 100 125
Bounds Checking
Once an array is created, it has a fixed size
14
Bounds Checking
For example, if the array score can hold 100 values, it
can be indexed using only the numbers 0 to 99
System.out.println (score[i]);
student
Chris,101,85
student[0]
student[1] Brad, 102,75.8
student[2]
student[3] Andrew, 103,75.9
Recursion
• Recursion is the process of defining something
in terms of itself.
• It allows a method to call itself.
compute()
• Complex to implement.
• Simple to implement.
}
TWO- DIMENSIONAL ARRAY
DECLARATION:-
Follow the same steps as that of simple arrays.
Example:-
int [ ][ ]; int chart[ ][ ] = new int [3][2];
chart = new int [3][2];
INITIALIZATION:-
15 16
int chart[3][2] = { 15,16,17,18,19,20}; 17 18
19 20
int chart[ ][ ] = { {15,16,17},{18,19,20} };
15 16 17
18 19 20
PROGRAM FOR PRACTISE
The daily maximum temperature is recorded in 5 cities during 3
days. Write a program to read the table elements into 2-d array
“temperature” and find the city and day corresponding to “ Highest
Temperature” and “Lowest Temperature” .