Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
UNIT
6.4
PROGRAMMING LANGUAGE (JAVA)
Basics of Array
OBJECTIVES
This unit helps you to understand the concept of array in Java. You will also
be able to write Java programs to store and retrieve values using an array.
At the end of this unit, you will be able to
Explain the fundamental concepts of array in Java.
Declare and initialise one-dimensional and two-dimensional arrays.
Access array elements.
Enter values into arrays.
Read values from arrays.
Benchmark Standard
Write simple program using one-dimensional and two-dimensional
arrays.
Let us Revise!
Introduction
In some situations, you have to write programs to handle large number of
variables with similar data type. Assume that you have to write a program to
accept the names of 100 students. One way of storing all the hundred names
is to declare 100 different variables in the program. This is a difficult and time-
consuming process. To overcome such problems, we can use arrays. Using
arrays you can store all the 100 variables as a single variable. Such a
collection of similar variables (for example, student name) having a common
name is called an array. In this unit, you will learn to write programs using
arrays.
columns. This array can hold up to four values. Figure 6.4.1 displays a one-
dimensional array that can hold four values.
Syntax
<Data type> <Variable name>[ ] = new <Data type>[Size of
the array]
Example
int marks[ ] = new int[5];
In Figure 6.4.2, marks is an array variable that can hold 5 values. Each value
is referred as an element. The array shown in Figure 6.4.2 will have five
elements of integer data type. Notice that the array size is specified within the
square brackets [ ]. This array contains only one subscript. You can use new
operator to create memory locations for the array marks.
Note
The subscript of an array always begins with 0 and ends with value one less than the array size
specified. The value of subscript is an integer, cannot be a negative number and must be
enclosed with [ ].
Initialisation is the process of assigning values to the array you have created.
Example for Initialisation
marks[0] = 95;
marks[1] = 85;
marks[2] = 75;
marks[3] = 80;
marks[4] = 65;
Refer to Figure 6.4.3, marks[0], marks[1] and marks[2] refers to the first,
second and third elements, respectively. The first element will always have
the array index as 0 as shown in Figure 6.4.4. Array index refers to the
location of the values in an array.
You can also initialise the array at the time of declaration as shown in the
following example:
int marks[] = {95,85,75};
When initialising an array, the values are enclosed within curly brackets { }.
Hands-On!
The following code illustrates how to declare an array, initialise it and access
its elements. Open the Student_Marks.java data file.
/* Program to declare and initialise an array */
class Student_Marks
{
public static void main(String args[])
Declares and initialises an
{ array.
for(int i=0;i<5;i++)
{
System.out.print("Enter the marks: ");
str = stdin.readLine();
marks[i] = Integer.parseInt(str);
}
Table 6.4.1 gives the details of the dry run for Code Segment 6.4.1
Hands-On!
This program accepts five marks from the user and prints the values on the
screen. Open the data file One_Int_Array.java.
import java.io.*;
This java package enables you
class One_Int_Array to use input/output statements.
{
public static void main(String args[]) throws
IOException This is to enable input
from keyboard.
{
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
String str;
One dimensional array
int marks[]=new int[6]; declaration.
Hands-On
Output
RUBIA
Activity 6.4.1
a. scores[0]
b. scores[1]
c. scores[-1]
d. scores[25]
Step 1: Open the data file PrintEven.java. The following Java program will be
present:
1. class PrintEven
2. {
3. public static void main(String args[])
4. {
5. int _____ = {2, 4, 6, 8};
6. System.out.println(ar[0] + " " + ar[1]);
7. }
8. }
Activity 6.4.2(b)
Step 1: Open the data file RestoreValue.java. The following Java statements
will be present:
1. class RestoreValue
2. {
3. public static void main(String args[])
4. {
5. int ar[] = {2, 4, 6, 8};
6. ar[0]=23;
7. ar[3]=ar[1];
8. System.out.println(ar[0] + " " + ar[3]);
7. }
8. }
Step 2: Read the program and write the output.
Step 3: Save, compile and execute the program.
Step 4: Check the output.
Step 1: Open the data file AssignValue.java. The following Java statements will
be present.
1. class AssignValue
2. {
3. public static void main(String args[])
4. {
5. int zip[ ] = new float[5];
6. zip[-1] = 7;
7. zip[1] = 3;
8. zip[2] = 4;
9. zip[3] = 1;
10. zip[4] = 9
11. System.out.println(zip[2+1]);
12. }
13. }
Lab Exercise
Lab Exercise 1: Write a Java program to find out the greatest and least values in an array.
Lab Exercise 2: Write a program to accept values using array and print the values in
ascending and descending order.
Lab Exercise 3: Write a program to accept two arrays and combine them into a single array.
Lab Exercise 4: Write a program to sort a one dimensional array of 10 elements.
2D
Row Column
Example
int marks_table[][] = new int[5][3];
Syntax
<Data type> <Variable name>[][] = new int[Row][Column];
Activity 6.4.3
1. Refer to Figure 6.4.8 and give the value of the following elements:
marks_table[0][0] =
marks_table[1][1] =
marks_table[3][0] =
marks_table[4][2] =
Hands-On!
int marks_table[ ][ ] = {
{83,99,74}, Storing 3 values
nd
in 2 row.
{88,90,72},
{89,88,82},
Storing 3 values in
{98,93,75}, 5th row.
{78,60,65}
};
System.out.println(marks_table[1][2]);
}
}
Code Sample 6.4.4
Output
72
Tip
If you try to access an array element that does not exist, Java Virtual Machine will generate an:
ArrayIndexOutOfBoundsException exception. For example, it is not meaningful to give the
statement marks_table[3.5][2].
Table 6.4.2 explains how the values are entered in a two-dimensional array.
Table 6.4.2: Dry Run for Entering Data into the Sample Two-Dimensional
Array
for(int x=0;x<2;x++)
{
for(int y=0;y<3;y++)
Prints the 2-row and 3-column array.
{
System.out.println("Marks : "+marks[x][y]);
}
}
Step 2: The condition for x is then checked. If the condition is true, that is if
the value of x is less than or equal to 2 the control is passed to
the inner loop.
Step 3: The value of y is initialised to 0. This value is used to refer to the
1st column.
Step 4: The condition for y is checked. If the condition is true, that is if the
value of y is less than or equal to 3, the control is passed to the
body of the loop.
Step 5: The println statement will print the value on the screen.
Step 6: The control is again passed to the inner for loop and the value of
y is incremented by 1.
Step 7: The steps 4, 5 and 6 are executed till the condition for y is false.
Step 8: When the condition for y is false, the control is passed to the outer
loop. Here, the value of x is incremented by 1.
Step 9: The steps 2 to 8 are executed till the condition for x is false.
Step 10: When the condition is false, the control comes out of the for
loop.
Hands-On
Program to illustrate how to accept the student index number and marks
obtained in Mathematics, Physics and Chemistry and display the total marks
for each student by adding all the marks of the student in different subjects.
Open the data file Two_Dim_Int_Array.java and execute it.
import java.io.*;
class Two_Dim_Int_Array
{
public static void main(String args[]) throws
IOException
{
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
Single dimensional array roll_no to
String m,r; store the roll number of 2 students.
int roll_no[]=new int[2];
Double dimensional array
int marks_table[][]=new int[2][3]; marks_table to store 3
subjects marks for 2 students.
int total[]=new int[2]; Single dimensional array total to store the sum of
marks in 3 subjects of each student.
for(int x=0;x<2;x++)
{ A for loop to accept roll number of 2 students.
if(y==2)
System.out.println("Enter the Chemistry
Marks:- ");
m = stdin.readLine();
marks_table[x][y] = Integer.parseInt(m);
total[x]=total[x]+marks_table[x][y];
} The total marks of 3 subjects for each student
is stored in array variable total.
}
Print statement to print the headings Roll No and
System.out.print("Roll subjects Maths, Physics and Chemistry.
No\tMaths\tPhysics\tChemistry\tTotal");
for(int x=0;x<2;x++) A for loop to print the roll number.
{
System.out.print("\n"+roll_no[x]);
A for loop to print three
for(int y=0;y<3;y++) subjects.
{
System.out.print("\t"+marks_table[x][y]);
}
System.out.print("\t\t"+total[x]);
}
}
}
Code Sample 6.4.5
Code Sample 6.4.5 accepts the roll number of 2 students and their marks in
Mathematics, Physics and Chemistry subjects, finds the total marks and
displays the roll number, each subject marks and total marks.
Output
Roll No Maths Physics Chemistry Total
1 83 99 74 256
2 88 90 72 250
Technical Terminologies
Summary
In this unit, you learnt the following:
Array is a collection of values of similar data types, stored in consecutive
memory locations.
Array index refers to the location of the values in an array.
The first element in an array will have the array index as 0.
When an array is declared, the size of the array has to be mentioned.
Arrays can be divided based on the number of subscripts used in the
array. They are:
• One-dimensional array.
• Two-dimensional array.
A one-dimensional array has one subscript.
Two-dimensional arrays have two subscripts.
Two-dimensional arrays will have n rows and m columns.
The number of elements in a two-dimensional arrays is n*m.
Assignment
1. Explain the need for arrays with an example.
2. Write a program to find the average of 10 numbers.
3. Write a program to accept 20 numbers from the user. Find the number
of odd and even numbers.
4. Give an example for a two-dimensional array.
5. How many values can the array x[4][2] store?
6. How many rows and columns are present in the array x[3][2]?
7. What is the array index of the 2nd element in a 3 x 2 matrix?
(matrix is a ccombination of rows and columns.)
Name
Subject: Programming Language (JAVA)
Unit: Basics of Array
Please tick [ ] the appropriate box when you have achieved the respective
competency
Comment
Competency codes: