Sei sulla pagina 1di 22

Fundamentals of Programming Programming Language (JAVA)

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.

Basics of Array 6.4-1


Fundamentals of Programming Programming Language (JAVA)

Let us Revise!

1. Define control statement.


2. List the types of control statements.
3. Define branching statement. Give an example for branching statement.
4. Define looping statement. Give an example.
5. What the differences between while loop and do while loop.

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.

6.4.1 Array Fundamentals


Definition: An Array is a collection of similar type of variables having a
common name. Values in array are stored in consecutive memory locations.
Arrays help in managing large number of variables. In this unit, you will learn
about the elements of an array, different types of arrays and the process of
declaring arrays.
Two types of arrays that are dealt in this unit are:
One-dimensional array
Two-dimensional array

6.4.2 One-Dimensional Array


Definition: One-dimensional array will have a single row and can have any
number of columns.
A one-dimensional array will have only one subscript. Subscript refers to the
dimension of the array. When you declare a one-dimensional array, for
example int x[] =new int[3];, it means that the array has one row and four

Basics of Array 6.4-2


Fundamentals of Programming Programming Language (JAVA)

columns. This array can hold up to four values. Figure 6.4.1 displays a one-
dimensional array that can hold four values.

Figure 6.4.1: Representation of a One-Dimensional Array

6.4.2 (A) Declaring and Initialising a One-Dimensional Array


You need to declare an array before using it in the program. An array can be
defined using different data types such as integer, double, float, char and so
on. However, all the values in an array must be of the same data type. For
example, consider that you are declaring an array to hold the marks of five
students. In this array, you can either have all the values of integer data type,
float data type or double data type based on the requirement. You cannot
store three integer values and two float values in the same array. The syntax
for declaring an array is as follows:

Syntax
<Data type> <Variable name>[ ] = new <Data type>[Size of
the array]
Example
int marks[ ] = new int[5];

Figure 6.4.2: Declaring and Creating an Array

Basics of Array 6.4-3


Fundamentals of Programming Programming Language (JAVA)

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;

Syntax for Initialising an Array Variable


<Variable name>[Array index] = Value;

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.

Figure 6.4.3: Array Elements

Basics of Array 6.4-4


Fundamentals of Programming Programming Language (JAVA)

Figure 6.4.4: Representation of Index in Array Elements

As represented in Figure 6.4.5, the values in an array are stored in


consecutive memory locations.

Figure 6.4.5: Array Elements Stored In Consecutive Memory Locations

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 { }.

6.4.2 (B) Accessing Array Elements in One-Dimensional Array


Using the array index you can access the array elements. To print the value of
the second element in an array, the code will be:
System.out.println("The second element:"+marks[1]);

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.

int marks[]={95,85,75,80,65}; Displays


st
the 1
System.out.print("\n marks[0] : "+marks[0]); element.

Basics of Array 6.4-5


Fundamentals of Programming Programming Language (JAVA)

System.out.print("\n marks[1] : "+marks[1]);


System.out.print("\n marks[2] : "+marks[2]); Displays the
nd
System.out.print("\n marks[3] : "+marks[3]); 2 element.

System.out.print("\n marks[4] : "+marks[4]);


}
}
Code Sample 6.4.1
Output
marks[0] : 95
marks[1] : 85
marks[2] : 75
marks[3] : 80
marks[4] : 65

In Code Sample 6.4.1, a one-dimensional array marks is intialised with values


The value in each element is printed using print( ) statement.

6.4.2 (C) Entering Data into an Array


Assume a situation where more number of values are to be stored in an array.
It is tedious to initialise the array elements one by one in a program. An
alternative method is to use a for loop in arrays to accept and display the
values. The sample code given in Code Segment 6.4.1 shows how to use a
for loop in an array.

for(int i=0;i<5;i++)
{
System.out.print("Enter the marks: ");
str = stdin.readLine();
marks[i] = Integer.parseInt(str);
}

Code Segment 6.4.1

The following steps explain the execution of Code Segment 6.4.1:


1. Initially, the value of i is initialised to 0. Now, marks[i] becomes
marks[0], which is the first element in the array.
2. The condition (i<5) is checked and if the condition is true, the next step
is executed.
3. The readLine( ) will accept the value from the user and store it in
variable str. The string value is converted to integer value using
parseInt( ) and the value is stored in marks[i]

Basics of Array 6.4-6


Fundamentals of Programming Programming Language (JAVA)

4. The value of the variable i is incremented by 1.


5. Steps 2, 3 and 4 are repeated till the condition becomes false. When
the condition is false, the control comes out of the for loop.

Table 6.4.1 gives the details of the dry run for Code Segment 6.4.1

Value of i Condition marks[i] Element


[ Array Index]
0 True x[0] 1st
1 True x[1] 2nd
2 True x[2] 3rd
3 True x[3] 4th
4 True x[4] 5th
Table 6.4.1: Dry Run for Entering Data into an Array

6.4.2 (D) Reading Data from an Array


You can use a for loop with a single println statement to print the values
from an array.
for(int i=0;i<5;i++)
{
System.out.println("Marks : "+marks[i]);
}
Code Segment 6.4.2

The following steps explain the execution of Code Segment 6.4.2:


1. Initially, the value of i is initialised to 0. Now, marks[i] becomes
marks[0], which is the first element in the array.
2. The condition (i<5) is now checked and if the condition is true, the next
step is executed.
3. Now the println statement will print the value on the screen.
4. The value of the variable i is incremented by 1.
5. Steps 2, 3 and 4 are repeated till the condition becomes false. When
the condition is false, the control comes out of the for loop.

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.

Basics of Array 6.4-7


Fundamentals of Programming Programming Language (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.

//Accepting the marks Initialize for loop to accept 5 values


for the array marks[].
for(int i=0;i<5;i++)
{
System.out.print("Enter mark"+(i+1)+" :");
str = stdin.readLine();
marks[i] = Integer.parseInt(str);
} Text data is received from
keyboard and converted to an
//Displaying the array integer.

for(int i=0;i<5;i++) For loop to display the array marks.


{
System.out.println("Marks "+(i+1)+" :
"+marks[i]);
}
Print statement to display the
} marks.
}
Code Sample 6.4.2
Output
Enter mark1 : 95
Enter mark2 : 87
Enter mark3 : 67
Enter mark4 : 85
Enter mark5 : 66
Marks 1 : 95
Marks 2 : 87
Marks 3 : 67
Marks 4 : 85
Marks 5 : 66

Basics of Array 6.4-8


Fundamentals of Programming Programming Language (JAVA)

In Code Sample 6.4.2,a one-dimensional array marks containing 6 elements is


declared. The for loop is used to accept the marks in 5 subjects and a for
loop is used to display the 5 subject marks.

Hands-On

Program to illustrate how to initialise a character array and display its


contents. Open the Onedim_Char_Array_Name.java file and execute it.

class Onedim_Char_Array_Name The characters in the


student name are stored in
{ the character array
public static void main(String args[]) stud_name.
{
char stud_name[]={'R','U','B','I','A'};
for(int i=0;i<=4;i++)
System.out.print(stud_name[i]);
} A for loop to print the student
} name.

Code Sample 6.4.3

Output
RUBIA

In Code Sample 6.4.3, a character array stud_name is initialized with a name


"RUBIA". Each element in the character array is printed using for loop and
println( ) statement.

Activity 6.4.1

1. Identify the array index of each element.


int ary[ ] = {2, 4, 6, 8}
a. 0, 1, 2, 3
b. 1, 2, 3, 4
c. 2, 4, 6, 8
d. 0, 2, 4, 6

2. int scores[ ] = new int[25];


Identify the valid elements in the following: Give reason for the same.

Basics of Array 6.4-9


Fundamentals of Programming Programming Language (JAVA)

a. scores[0]
b. scores[1]
c. scores[-1]
d. scores[25]

Activity 6.4.2 (a)

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. }

Step 2: Fill in the blank with correct statement.


Step 3: Save, compile and execute the program.

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.

Basics of Array 6.4-10


Fundamentals of Programming Programming Language (JAVA)

Activity 6.4.2 (c)

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. }

Step 2: Compile the program.


Step 3: Correct the errors and save the program.
Step 4: Execute the program.

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.

6.4.3 Two-Dimensional Array


Definition: Two-dimensional arrays are arrays with more than one dimension.
Two-dimensional array is a collection of a number of one-dimensional arrays
placed one below the other. Two-dimensional arrays represent data in terms
of rows and columns. It has two subscripts.

Basics of Array 6.4-11


Fundamentals of Programming Programming Language (JAVA)

2D

Figure 6.4.6: A Representation of Two-Dimensional Array

6.4.3 (A) Declaring and Initialising a Two-Dimensional Array


Assume that there are 5 students in a class and each of them study three
different subjects, for example Mathematics, Physics and Chemistry. The
marks of each student in all three subjects can be represented in a single row
as shown in Figure 6.4.7.

Figure 6.4.7: Example for One-Dimensional Array Representation

The marks of the 5 students in each subject need to be represented in 5


different rows as shown in Figure 6.4.8.

Basics of Array 6.4-12


Fundamentals of Programming Programming Language (JAVA)

Figure 6.4.8: Example for Two-Dimensional Array Representation

The two-dimensional array shown in Figure 6.4.8 can be declared as:

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] =

Basics of Array 6.4-13


Fundamentals of Programming Programming Language (JAVA)

6.4.3 (B) Accessing Array Elements in Two-Dimensional Array


You can use the row and column array index to access the array elements.
For example, if you need to print the value stored in first row and second
column of the array marks_table, (i.e. chemistry mark of student 2) the code
will be as follows:
Example
System.out.println(marks_table[1][2])

The example will produce the output: 72

Hands-On!

Program to illustrate how to declare a two dimensional array, initialise it and


access its elements: Open the data file twodim_array_students_marks.java and
execute it.
/* Program to declare and initialise an array */
class Twodim_Array_Students_Marks
{
public static void main(String args[]) Storing 3 values in
{ 1st row.

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].

Basics of Array 6.4-14


Fundamentals of Programming Programming Language (JAVA)

6.4.3 (C) Entering Data into an Array


You can use a for loop to accept marks of 2 students in 3 subjects.

for(int x=0;x<2;x++) For loop to accept total


number of rows.
{
for(int y=0;y<3;y++) For loop to accept total
number of columns.
{
m = stdin.readLine();
Text data is
marks_table[x][y] = Integer.parseInt(m); received from
keyboard and
} converted to an
integer.
}
Code Segment 6.4.3

The following steps explain the execution of Code Segment 6.4.3:


1. First, the value of x is initialised to zero and this value is used to refer to
the 1st row.
2. The condition in the first for loop 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.
3. The value of y is initialised to zero and this value is used to refer to the 1st
column.
4. The condition for y is checked. If the condition is true, that is if y is less
than or equal to 3, the control is passed to the body of the loop.
5. The readLine( ) method will accept the value from the user.
6. The control again passes to the inner for loop. Here, the value of y is
incremented by 1.
7. The steps 4, 5 and 6 are executed till the condition for y is false.
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.
9. The steps 2 to 9 are executed till the condition for x is false.
10. When the condition becomes false, the control comes out of the for loop.

Basics of Array 6.4-15


Fundamentals of Programming Programming Language (JAVA)

Table 6.4.2 explains how the values are entered in a two-dimensional array.

Value Condition Valu Condition


marks_table
of for x e of for j Element
[ x ][ y ]
X (x<3) y (y<5)
marks_table[0]
0 True 0 True 1st
[0]
marks_table[0]
0 - 1 True 2nd
[1]
marks_table[0]
0 - 2 True 3rd
[2]
marks_table[1]
1 True 0 True 4th
[0]
marks_table[1]
1 - 1 True 5th
[1]
marks_table[1]
1 - 2 True 6th
[2]

Table 6.4.2: Dry Run for Entering Data into the Sample Two-Dimensional
Array

6.4.3 (D) Reading Data from an Array


You can use a for loop with println statement to print the values from an
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]);
}
}

Code Segment 6.4.4

The following steps explain the execution of Code Segment 6.4.4:


Step 1: The value of x is initialised to 0. This value is used to refer to the
1st row.

Basics of Array 6.4-16


Fundamentals of Programming Programming Language (JAVA)

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.

Basics of Array 6.4-17


Fundamentals of Programming Programming Language (JAVA)

for(int x=0;x<2;x++)
{ A for loop to accept roll number of 2 students.

System.out.println("Enter roll number of


student:- ");
Array variable roll_no to
r = stdin.readLine(); store roll number of 2
students.
roll_no[x] = Integer.parseInt(r);
for(int y=0;y<3;y++)
{ For loop to accept 3 subject marks for
2 students.
if(y==0)
System.out.println("Enter the Maths Marks:-“);
if(y==1)
System.out.println("Enter the Physics Marks:- ");

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

Basics of Array 6.4-18


Fundamentals of Programming Programming Language (JAVA)

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

Self-Check Exercise 6.4.1

Fill in the blanks


1. An _____ is a collection of similar type of variables having a common name.
2. One-dimensional array will have a single row and can have any number of columns.
3. Array elements can be accessed using _____ statements.
4. _________ arrays have two subscripts.
5. In an array marks[4] represent the ____ element.

Activity 6.4.3 (a)

1. Examine the following:


double values[ ] [ ] = {
{1.2, 9.0, 3.2},
{9.2, 0.5, 1.5, -1.2},
{7.3, 7.9, 4.8}
};
What is the value of values[2][1]?
a. 7.3
b. 7.9
c. 9.2
d. There is no such array element
2. You need to create a table as given here.
12 -9 8
7 14
-32 -1 0

Basics of Array 6.4-19


Fundamentals of Programming Programming Language (JAVA)

Choose the correct declaration from the declaration statements given:

Declaration A Declaration B Declaration C Declaration D


Double table [ ][ double table[ ][ ] = double table[ ][ ] = double table[ ][ ] =
]= { {12, -9, 8}, { {12, -9, 8} { {12, -9, 8},
{7, 14, 0}, {7, 14} {7, 14},
{ 12, -9, 8,
-32, -1, 0} }; {-32, -1, 0} }; {-32, -1, 0} };
7, 14,
-32, -1, 0} ;

3. Which of the following statements constructs an array with 5 rows of 7


columns?
long stuff[ ][ ] = new stuff[5][7];

long stuff[ ][ ] = new long[5][7];

long stuff[ ][ ] = long[5][7];

long stuff[ ][ ] = long[7][5];

4. Which of the following statements constructs a two-dimensional array


with 7 rows?
int array[ ][ ] = new int[7][ ];
int array[ ][ ] = new int[7];
int array[ ][ ] = new int[ ][7];
int[] array[7] = new int[ ];

Technical Terminologies

Array – It is a collection of values having similar data types,


stored in consecutive memory locations.
Array Element – Array Element refers to each data item in an array.
Array Index – Array Index refers to the location of the values in an
array.

Basics of Array 6.4-20


Fundamentals of Programming Programming Language (JAVA)

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.)

Basics of Array 6.4-21


Fundamentals of Programming Programming Language (JAVA)

Criterion Referenced Test


Instruction: Students must evaluate themselves to achieve the following
competencies listed below

Name
Subject: Programming Language (JAVA)
Unit: Basics of Array

Please tick [ ] the appropriate box when you have achieved the respective
competency

Date Basics of Array


C1 C2 C3 C4 C5 C6 C7 C8 C9 C10

Comment

Competency codes:

C1 = Identify the need for arrays.


C2 = Identify the types of arrays.
C3 = Identify the various components (index, elements, subscript and so on)
in an array.
C4 = Write programs using arrays.
C5 = Identify the need for arrays.
C6 = Declare and initialise two-dimensional arrays.
C7 = Access data from two-dimensional arrays.
C8 = Accept data into two-dimensional array.
C9 = Display the data from two-dimensional array.
C10 = Write programs using two-dimensional arrays.

Basics of Array 6.4-22

Potrebbero piacerti anche