Java LAB 3

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

Arrays in Java Lab # 3

LAB # 3

ARRAYS

OBJECTIVE:
To Study Java One Dimentional and Two Dimentional Arrays.

THEORY:

3.1 ARRAYS

Array Variables:
An array variable and the array it refers to are separate entities. The memory
that is allocated for an array variable stores a reference to an array object, not
the array itself. The array object itself is a distinct entity that will be elsewhere
in memory. All variables that refer to objects store references that record the
memory locations of the objects they refer to. You are not obliged to create an
array when you declare an array variable. You can first create the array
variable and later use it to store a reference to a particular array. You could
declare the integer array variable primes with the following statement:

You may come across an alternative notation for declaring an


array variable:

Defining an Array:

Once you have declared an array variable, you can define an array that it will
reference:

Object Oriented Programming - OOPs 1


Arrays in Java Lab # 3

This statement creates an array that will store 10 values of type int, and stores
a reference to the array in the variable primes. The reference is simply where
the array is in memory. You could also declare the array variable and define
the array of type int to hold
10 prime numbers with a single statement;

Initializing Arrays:

You can initialize the elements in an array with your own values when you
declare it, and at the same time determine how many elements it will have. To
do this, you simply add an equals sign followed by the list of element values
enclosed between braces following the specification of the array variable. For
example, you could define and initialize an array with the following statement:

This creates the primes array with sufficient elements to store all of the
initializing values that appear between the braces — seven in this case. The
array size is determined by the number of initial values so no other
information is necessary to define the array. The values are assigned to the
array elements in sequence so in this example:
primes[0] will have the initial value 2,
primes[1]will have the initial value 3,
primes[2]will have the initial value 5,
and so on through the rest of the elements in the array.

If you specify initializing values for an array, you must include values for all
the elements. If you want to set only some of the array elements to specific
values explicitly, you must use an assignment statement for each element for
which you supply a value. For example:

Object Oriented Programming - OOPs 2


Arrays in Java Lab # 3

The first statement declares and defines an integer array of 100 elements, all
of which will be initialized to zero by default. The two assignment statements
then set values for the first two array elements. You can also initialize the
elements in an array using a for loop to iterate over all the elements and set
the value for each:

For an array with length elements, the index values for the elements run from
0 to length-1. The for loop control statement is written so that the loop
variable i starts at 0 and will be incremented by 1 on each iteration up to
data.length-1. When i is incremented to data.length, the loop will end. Thus,
this loop sets each element of the array to 1. Using a for loop in this way is
one standard idiom for iterating over the elements in an array.

Arrays of Characters:

All the arrays you have defined have contained elements storing numerical
values so far. You can also have arrays of characters. For example, you can
declare an array variable of type char [ ] to hold 50 characters with the
following statement:

You can also define the size of an array of type char[]by the characters it holds initially:

This defines an array of five elements, initialized with the characters appearing between
the braces. This is fine for things like vowels, but what about proper messages?
Using an array of type char
Well, you get the message — just — but it’s not a very friendly way to deal with it. It
looks like a collection of characters, which is what it is, but still gives you the ability to
get at the individual characters if you want.

One-Dimensional Arrays:

Object Oriented Programming - OOPs 3


Arrays in Java Lab # 3

A one-dimensional array is, essentially, a list of like-typed variables. To create an


array, you first must create an array variable of the desired type. The general form of a
one dimensional array declaration is

int month_days[];

Although this declaration establishes the fact that month_days is an array variable,
no array actually exists. In fact, the value of month_days is set to null, which
represents an array with no value. To link month_days with an actual, physical array
of integers, you must allocate one using new and assign it to month_days. new is a
special operator that allocates memory.
The general form of new as it applies to one-dimensional arrays appears as follows:

array-var = new type[size];

It is possible to combine the declaration of the array variable with the allocation of
the array itself, as shown here:

int month_days[] = new int[12];

Prorgam # 1
This program fill an array of 10 elements by randomly generated Integers,
range (1-100).

import java.lang.Math;
public class array1
{
public static void main(String args[])
{
int a[] = new int [10];
for (int i=0;i<10;i++)
a[i]=(int)(Math.random()*100);

System.out.println("Values are");
for (int i=0;i<10;i++)
System.out.println(a[i]);
}
}

Output:

Object Oriented Programming - OOPs 4


Arrays in Java Lab # 3

3.2 ARRAYS OF ARRAYS

Multidimensional Arrays:
In Java, multidimensional arrays are actually arrays of arrays. These, as you might
expect, look and act like regular multidimensional arrays.
For example, the following declares a two-dimensional array variable called twoD.

int twoD[][] = new int[4][5];

It is possible to initialize multidimensional arrays. To do so, simply enclose each


dimension’s initializer within its own set of curly braces. The following program
creates a matrix where each element contains the product of the row and column
indexes. Also notice that you can use expressions as well as literal values inside of
array initializers.

// Initialize a two-dimensional array.

Object Oriented Programming - OOPs 5


Arrays in Java Lab # 3

class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}

Output:

When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension. You can allocate the remaining dimensions
separately.

when you allocate dimensions manually, you do not need to allocate the same number
of elements for each dimension. As stated earlier, since multidimensional arrays are
actually arrays of arrays, the length of each array is under your control. For example,
the following program creates a two dimensional array in which the sizes of the
second dimension are unequal.

Prorgam # 2
This program manually allocate differing size second dimensions.

public class array2 {


public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)

Object Oriented Programming - OOPs 6


Arrays in Java Lab # 3

for(j=0; j<i+1; j++) {


twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

Output:

LAB TASK

1. Write a program that reads (fictitious) student test scores in the


range 0 through 100 and print the following statistics to two decimal
places:

The average (mean) score.


The student with the highest score.
The student with the lowest score.
The number of students whose score equal or exceed the average.

For each student:

The difference between the average score and the student’s score (this
can be either positive or negative).
The grade letter where
A is a score of 90 or greater.
B is a score of 80 through 89.99.
C is a score of 70 through 79.99
D is a score of 60 through 69.99
E is a score of less than 60.

Object Oriented Programming - OOPs 7


Arrays in Java Lab # 3

2. The problem is to write a program that picks four cards randomly


from a deck of 52 cards. All the cards can be represented using an
array named deck, filled with initial values 0 to 51, as follows:
Int [ ] deck = new int[52];
// Initialize cards for (int i = 0; i < deck.length; i++) deck[i] = i;
Card numbers 0 to 12, 13 to 25, 26 to 38, 39 to 51 represent 13
Spades, 13 Hearts, 13 Diamonds, and 13 Clubs, respectively, as
shown in Figure 6.3. After shuffling the array deck, pick the first four
cards from deck.

3. Write a program to wander around 10 different locations and find


their average temperature of a year, you’ll generate the temperatures
as random values between -10 degrees and 35 degrees. This assumes
you are recording temperatures in degrees Celsius. If you prefer
Fahrenheit, you could generate values from 14 degrees to 95 degrees
to cover the same range.

Expected Output:
Average temperature at location 1 = 12.2733345
Average temperature at location 2 = 12.012519
Average temperature at location 3 = 11.545245…continue till location 10.

Object Oriented Programming - OOPs 8

You might also like