0% found this document useful (0 votes)
12 views8 pages

Java Arrays: One & Two Dimensional Guide

This document describes a lab assignment on arrays in Java. It covers one-dimensional and two-dimensional arrays, initializing arrays, arrays of characters, and multidimensional arrays. It includes two programming tasks: 1) A program to analyze student test scores stored in an array, calculating statistics and grades. 2) A program to pick four random cards from a deck represented by a 52-element integer array.

Uploaded by

Karan Kukreja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views8 pages

Java Arrays: One & Two Dimensional Guide

This document describes a lab assignment on arrays in Java. It covers one-dimensional and two-dimensional arrays, initializing arrays, arrays of characters, and multidimensional arrays. It includes two programming tasks: 1) A program to analyze student test scores stored in an array, calculating statistics and grades. 2) A program to pick four random cards from a deck represented by a 52-element integer array.

Uploaded by

Karan Kukreja
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

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
[Link]-1. When i is incremented to [Link], 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 [Link];
public class array1
{
public static void main(String args[])
{
int a[] = new int [10];
for (int i=0;i<10;i++)
a[i]=(int)([Link]()*100);

[Link]("Values are");
for (int i=0;i<10;i++)
[Link](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++)
[Link](m[i][j] + " ");
[Link]();
}
}
}

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++)
[Link](twoD[i][j] + " ");
[Link]();
}
}
}

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 < [Link]; 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

Common questions

Powered by AI

Initializing a two-dimensional array with expressions within array initializers enhances code readability by making the array's pattern of stored values clear and expressive directly in the initialization, such as using 'row * column' to assign values based on indices. This directly encodes logical or mathematical relationships among elements, improving the array's functionality concerning these relationships without needing additional loops or conditions to assign these values later in the code .

Character arrays in Java provide advantages such as simplicity and direct access to individual characters, making them useful in applications where granular character manipulation is required, like parsers or tokenizers. Treating strings as arrays of characters allows programmers to process each character efficiently, but it also implies a lower level of abstraction compared to using the String class, which handles immutability and string-level operations more robustly .

Using arrays to store student test scores allows efficient handling of indexed data, enabling quick access and manipulation of scores for statistical calculations, such as finding averages or determining maximum scores. Arrays are beneficial for their simplicity and ease of implementation; however, they have limitations such as fixed size and lack of flexibility in adding or removing elements. Complex statistics might require additional data structures or algorithms that are less straightforward to implement with basic one-dimensional arrays .

Manually allocating different sizes for dimensions of a two-dimensional array in Java can be beneficial in applications that require triangular or ragged arrays, where each row contains a varying number of columns. This flexibility allows for more efficient use of memory by accommodating datasets with non-uniform structures, such as in dynamic data analysis where relationships between data points vary, or in simulations where each scenario's complexity might change .

Random initialization of Java arrays, such as shuffling a card deck, involves filling the array with a sequence of values—in this case, representing cards—and then rearranging them randomly to simulate shuffling. This process is significant as it models real-world randomness and unpredictability in applications like games. By efficiently using loops and random number generation methods, a seemingly ordered array can become randomized, mirroring shuffles or similar real-life occurrences .

Challenges in using arrays to calculate average temperatures include handling the precision of floating-point numbers and ensuring data accuracy over large datasets. Arrays require managing loop iterations carefully to compute means without arithmetic overflow or floating-point errors. Mitigating these issues involves using properly sized data types like double for high precision, ensuring the logic within loops correctly manages index boundaries, and possibly implementing additional checks for data validation to handle outliers or unexpected values .

In Java, multidimensional arrays are essentially arrays of arrays, which impacts their memory allocation by requiring separate memory locations for each sub-array. This means each sub-array can have a different length, offering more flexibility but also requiring careful management of memory and access. For example, allocating the first (leftmost) dimension does not automatically allocate the subsequent dimensions; these must be allocated individually, allowing for triangular arrays or arrays with uneven rows .

A for loop is significant for array initialization in Java as it provides a systematic way to set each element to a specific value, allowing for programmatically determined values rather than static ones. This method is flexible and efficient, especially when dealing with large arrays. Compared to direct initialization with curly braces, which is limited to explicitly provided values, a for loop can handle runtime decisions about element values and accommodate complex initialization logic .

An array variable declaration in Java creates a variable that holds a reference to the array, but does not yet allocate memory for the array itself. Memory allocation for the actual array object happens separately and can occur later in the code. When you define an array, you allocate memory for it using the 'new' keyword, which assigns a memory location to the array and allows the array variable to hold the reference to this location .

Java's array handling showcases core OOP principles by treating arrays as objects capable of storing references, encapsulating a collection of elements that can interact with each other via their indices. Arrays also embody the concept of abstraction, as they allow for complex data manipulation without necessitating focus on underlying memory allocation or management. Furthermore, arrays, when combined with objects, illustrate encapsulation and modularization by integrating array-based data handling within larger object-oriented architectures .

You might also like