COS202 Lecture 3b
COS202 Lecture 3b
LECTURE 3
JAVA ARRAY
Continuation
To demonstrate a practical example of using arrays, let's create a program that calculates the
average of different scores.
Example 3.5
1 public class Main {
2 public static void main(String[] args) {
3
4 int[] scores = {45, 21, 63, 56, 70, 18, 57, 82};
5
6 float avg, sum = 0;
7
8 int arrayLength = scores.length;
9
10 for (int score : scores) {
11 sum += score;
12 }
13
14 avg = sum / arrayLength;
15 System.out.println("The average score is: " + avg);
16
17 }
18 }
In example 3.6, we create a program that finds the maximum age among different ages.
Example 3.6
1 public class Main {
2 public static void main(String[] args) {
3
4 int[] ages = {17, 50, 22, 35, 65, 18, 43, 38};
5
6 int arrayLength = ages.length;
7
8 int maxAge = ages[0];
9
10 for (int age : ages) {
11 if (age >= maxAge) {
12 maxAge = age;
13 }
14 }
15
16 System.out.println("The maximum age in the array is: " + maxAge);
17 }
18 }
In order to enter elements into an array at runtime, example 3.7 shows the size of elements that
can be entered into the array and also display the result.
Example 3.7
1 import java.util.Scanner;
2
3 public class Main {
4 public static void main(String[] args) {
5 int[] numbers = new int[3]; // Array to hold 3 integers
6 Scanner myInput = new Scanner(System.in);
7
8 // Taking input
9 System.out.println("Enter 3 numbers:");
10 for (int i = 0; i < 3; i++) {
11 numbers[i] = myInput.nextInt();
12 }
13
14 // Displaying the array elements
15 System.out.println("You entered:");
16 for (int i = 0; i < 3; i++) {
17 System.out.println(numbers[i]);
18 }
19
20 myInput.close();
21 }
22 }
Multidimensional Array
A multidimensional array is an array of arrays. Multidimensional arrays are useful when you
want to store data as a tabular form, like a table with rows and columns. To create a
two-dimensional array, add each array within its own set of curly braces.
Syntax
dataType[][] variableName = { {value0, … valuek}, { value0, … valuek } };
To access the elements of the variableName array, specify two indexes: one for the array, and
one for the element inside that array. Example 3.8 accesses the third element [2] in the second
array [1] of justNum:
Example 3.8
1 public class Main {
2 public static void main(String[] args) {
3
4 int[][] justNum = {{3, 8, 11, 4, 15, 0} {5, 12, 1, 6}};
5
6 System.out.println(justNum[1][2]);
7 }
8 }
Or you could just use a for-each loop, which is considered easier to read and write as shown in
example 3.10.
Example 3.10
1 public class Main {
2 public static void main(String[] args) {
3
4 int[][] justNum = {{3, 8, 11, 4, 15, 0} {5, 12, 1, 6}};
5
6 for (int[] row : justNum) {
7 for (int i : row) {
8 System.out.println(i);
9 }
10 }
11 }
12 }
ASSIGNMENT
Using a nested for loop statement, write a Java program to print numbers in a 4 by 3 matrix