0% found this document useful (0 votes)
262 views

Chapter 2 Non Primitive Data Types

This document discusses non-primitive data types including arrays, lists, and files. It provides details on one-dimensional and multi-dimensional arrays, including how to declare, instantiate, access elements, and get the length of an array. Array elements are accessed using indexes from 0 to length-1. Multidimensional arrays are implemented as arrays of arrays.

Uploaded by

BENJIE ZARATE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
262 views

Chapter 2 Non Primitive Data Types

This document discusses non-primitive data types including arrays, lists, and files. It provides details on one-dimensional and multi-dimensional arrays, including how to declare, instantiate, access elements, and get the length of an array. Array elements are accessed using indexes from 0 to length-1. Multidimensional arrays are implemented as arrays of arrays.

Uploaded by

BENJIE ZARATE
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Chapter 2

Non Primitive Data Types

Chapter Objectives

In this chapter, you will learn more about what is a Data Structure and Algorithms is and
how it actually functions. At the end of this chapter, students will be able to:
 Create a way to apply the properties of Non primitive data type
 Design and implement array and its application
 Apply the two addressing methods - computed addressing and link addressing

Non primitive Data Type


 These are more sophisticated data structures.
 These are derived from primitive data structures.
 The non-primitive data structures emphasize on structuring of a group of homogeneous
or heterogeneous data items.
 Examples of Non-primitive data type are Array, List, and File etc.

A Non-primitive data type is further divided into Linear and Non-Linear data structure
 Array: An array is a fixed-size sequenced collection of elements of the same data type.
 List: An ordered set containing variable number of elements is called as Lists.
 File: A file is a collection of logically related information. It can be viewed as a large list of
records consisting of various fields.

1. Array
 It is a finite sequence of data items occupying a continuous set of memory locations, all
of which are of the same type.
 Set of homogeneous elements.
 An array is a data structure
 Used to process multiple elements with the same data type when a number of such
elements are known.
 An array is a composite data structure; that means it had to be constructed from basic
data types such as array integers.

Direct or random access means that each element can be accessed simply by specifying its
location in the array. Sequential access means that an element can only be accessed by first
processing all those that precede it. Index or subscript specifies the position of an element in the
array. One-dimensional Array requires only one index to access an element. Base address refers
to the address of the first memory cell used to store the elements. Multi-dimensional Array
requires 2 or more indices to access a single element of the array.

Memory Address Types:


1. byte addressable (1 memory cell = 1 byte)
2. word addressable (1 memory cell = 2 bytes)

1. One dimensional Array


int A[4];

data type Index/subscript


var name

0 1 2 3
2. Two dimensional Array
int B[5][4];

0 1 2 3
0
1
2
3
4
0 1 2 3
0 0

3. 3 dimensional Array 1 1
int C[3][5][4]; 2 2

3
4

4. 4 dimensional Array
int D[2][3][5][4];

0 1 2 3 0 1 2 3
0 0 0
0
1 1 1
1
2 2 2
2
3 3
4 4

0
1

Declaring Arrays
When declaring an array, you list the data type, followed by a set of square brackets [],
followed by the identifier name. For example,
int []ages;
or you can place the brackets after the identifier. For example,
int ages[];
After declaring, we must create the array and specify its length with a constructor statement.
This process in Java is called instantiation (the Java word for creates). In order to instantiate an
object, we need to use a constructor for this. Take note, that the size of an array cannot be
changed once you've initialized it. For example,
//declaration
int ages[];
//instantiate object
ages = new int[100];
or, can also be written as,
//declare and instantiate object
int ages[] = new int[100];
In the example, the declaration tells the Java Compiler that the identifier ages will be used as
the name of an array containing integers, and to create or instantiate a new array containing
100 elements.

Instead of using the new keyword to instantiate an array, you can also automatically declare,
construct and assign values at once.
Examples are,
//creates an array of Boolean variables with identifier
//results. This array contains 4 elements that are
//initialized to values {true, false, true, false}
boolean results[] ={ true, false, true, false };
//creates an array of 4 double variables initialized
//to the values {100, 90, 80, 75};
double []grades = {100, 90, 80, 75};

//creates an array of Strings with identifier days and


//initialized. This array contains 7 elements
String days[] = { “Mon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”, “Sun”};

Accessing an array element


To access an array element, or a part of the array, you use a number called an index or subscript.
An index number or subscript is assigned to each member of the array, allowing the program
and the programmer to access individual values when necessary. Index numbers are always
integers. They begin with zero and progress sequentially by whole numbers to the end of the
array. Take note that the elements inside your array is from 0 to (sizeOfArray-1). For example,
given the array we declared a while ago, we have

//assigns 10 to the first element in the array


ages[0] = 10;
//prints the last element in the array
System.out.print(ages[99]);

Take note that once an array is declared and constructed, the stored value of each member of
the array will be initialized to zero for number data. However, reference data types such as Strings
are not initialized to blanks or an empty string “”. Therefore, you must populate the String arrays
explicitly. The following is a sample code on how to print all the elements in the array. This uses
a for loop, so our code is shorter.

public class ArraySample


{
public static void main( String[] args )
{
int[] ages = new int[100];
for( int i=0; i<100; i++ )
{
System.out.print( ages[i] );
}
}
}

Coding Guidelines:
1. It is usually better to initialize or instantiate the array right away after you declare it.
For example, the declaration,
int []arr = new int[100];
is preferred over,
int []arr;
arr = new int[100];
2. The elements of an n-element array have indexes from 0 to n-1. Note that there is no
array element arr[n]! This will result in an array-index-out-of-bounds exception.
3. You cannot resize an array.
Array length
In order to get the number of elements in an array, you can use the length field of an array. The
length field of an array returns the size of the array. It can be used by writing,
arrayName.length
For example, given the previous example, we can re-write it as,

public class ArraySample


{
public static void main( String[] args )
{
int[] ages = new int[100];
for( int i=0; i<ages.length; i++ )
{
System.out.print( ages[i] );
}
}
}

Coding Guidelines:

1.When creating for loops to process the elements of an array, use the array object's
length field in the condition statement of the for loop. This will allow the loop to adjust
automatically for different-sized arrays.
2.Declare the sizes of arrays in a Java program using named constants to make them easy
to change. For example,

final int ARRAY_SIZE = 1000; //declare a constant


...
int[] ages = new int[ARRAY_SIZE];

Multidimensional Arrays
Multidimensional arrays are implemented as arrays of arrays. Multidimensional arrays are
declared by appending the appropriate number of bracket pairs after the array name. For
example,

// integer array 512 x 128 elements


int[][] twoD = new int[512][128];
// character array 8 x 16 x 24
char[][][] threeD = new char[8][16][24];

// String array 4 rows x 2 columns


String[][] dogs = {{ "terry", "brown" }, { "Kristin", "white" }, { "toby", "gray"}, { "fido",
"black"}};

To access an element in a multidimensional array is just the same as accessing the elements in a
one dimensional array. For example, to access the first element in the first row of the array dogs,
we write,

System.out.print( dogs[0][0] );

This will print the String "terry" on the screen.

Addressing Methods

In creating a data structure, it is important to determine how to access the data items. It is
determined by the addressing method used. There are two types of addressing methods in
general:

1. computed ddressing method, and


2. link addressing method.

Computed Addressing Method

Computed addressing method is used to access the elements of a structure in preallocated space.
It is essentially static, an array for example:

int x[] = new int[10];

A data item can be accessed directly by knowing the index on where it is stored.

General Formula: (1 dimensional array)

address(A[e]) =base(A) + e *esize or Address of A [ I ] = B + W * ( I – LB )


where,

A is the array name = B - Base address


e is the array element = W - Storage Size of one element
stored in the array (in byte)
esize is the size (in bytes) occupied by the element of the
array = ( I – LB )
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified
assume 0 (zero)

Word addressable (1MC = 16 bits)

Example
1. short int A[4];
find A[3]
Solution:
esize = 2 =Short int
e= 3

note: element size depends on the name of array it goes as follows:


int = 4
byte = 1
char = 2
float = 4
double = 8
short int = 2

address(A[e]) =base(A) + e *esize = base(A) + ( 3*2)


=base(A) + 6

2. Given the base address of an array B[1300…..1900] as 1020 and size of each element is 2
bytes in the memory. Find the address of B[1700].

Solution:

The given values are: B = 1020, LB = 1300, W = 2, I = 1700

Address of A [ I ] = B + W * ( I – LB )
= 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820

General Formula: (2 dimensional array, byte addressable)

 Row wise

address(B[i][j]) =base(B) + [(i*c) + j] *esize

Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]

 Colum wise

Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]

address(B[i][j]) =base(B) + [i+( j*d)] *esize

where,
B is the array name
i is index row =I = ( I – Lr )
j is index column =J = ( J – Lc )
c is the total number of columns = N
d is the total number of columns = M
esize is the size (in bytes) occupied by the element of the array = W

NOTE: Usually number of rows and columns of a matrix are given (like A [20][30] or A[40][60] )
but if it is given as A[Lr- – – – – Ur, Lc- – – – – Uc]. In this case number of rows and columns are
calculated using the following methods:
 Number of rows (M) will be calculated as = (Ur – Lr) + 1
 Number of columns (N) will be calculated as = (Uc – Lc) + 1
http://www.guideforschool.com/625348-memory-address-calculation-in-an-array/

And rest of the process will remain same as per requirement (Row Major Wise or Column Major
Wise).

Example.

1. An array X [-15……….10, 15……………40] requires one byte of storage. If beginning


location is 1500 determine the location of X [15][20] using column wise and row wise

Solution:

As you see here the number of rows and columns are not given in the question. So they
are calculated as:

Number or rows say M = (Ur – Lr) + 1 = [10 – (- 15)] +1 = 26


Number or columns say N = (Uc – Lc) + 1 = [40 – 15)] +1 = 26

Column Major Wise Calculation of above equation


Given values are: B = 1500, W = 1 byte, I = 15, J = 20, Lr = -15, Lc = 15, M = 26

Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]

= 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)]


= 1500 + 1 * [30 + 26 * 5]
= 1500 + 1 * [160]
= 1660

Row Major Wise Calculation of above equation


Given values are: B = 1500, W = 1 byte, I = 15, J = 20, Lr = -15, Lc = 15, N = 26

Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]

= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)]


= 1500 + 1 * [26 * 30 + 5]
= 1500 + 1 * [780 + 5]
= 1500 + 785
= 2285

2. double x[36][42];
Find x[23][38] using column and row wise
Solution:
c= total column size = 42
d= total row size = 36
esize =double = 8
i= 23
j= 38

row wise

address(B[i][j]) =base(B) + [(i*c) + j] *esize

= base(B) + [ (23*42) +38] *8

= base(B) + 8032

column wise

address(B[i][j]) =base(B) + [i+( j*d)] *esize

= base(B) + [ (23+ (38*36)] *8

= base(B) + 11128

Applications of Array

Symbol Manipulation (matrix representation of polynomial equation)

a. Sparse Matrix
b. Symbol Manipulation using Array

We can use array for different kind of operations in polynomial equation such as addition,
subtraction, division, differentiation etc…

We are interested in finding suitable representation for polynomial so that different operations
like addition, subtraction etc… can be performed in efficient manner

Array can be used to represent Polynomial equation


Once we have algorithm for converting the polynomial equation to an array representation and
another algorithm for converting array to polynomial equation, then different operations in array
(matrix) will be corresponding operations of polynomial equation

What is sparse matrix?

 An mXn matrix is said to be sparse if “many” of its elements are zero.


 A matrix that is not sparse is called a dense matrix.
 We can device a simple representation scheme whose space requirement equals the size
of the nonzero elements.
 2 dimensional array is used to represent a sparse matrix in which there are 3 rows named
as
1. row - index of row, where non zero element is located, it is the horizontal line
2. column - index of column, where non zero element is located, it is the vertical line
3. value - value of non zero element located at index

Example:-

 The non-zero entries of a sparse matrix may be mapped into a linear list in row-major
order.
1. For example the non-zero entries of 4X8 matrix of below fig.(a) in row major order are
2, 1, 6, 7, 3, 9, 8, 4, 5
To construct matrix structure we need to record

a. Original row and columns of each non zero entries


b. No of rows and columns in the matrix
So each element of the array into which the sparse matrix is mapped need to have three fields:
row, column and value

A corresponding amount of time is saved creating the linear list representation over initialization
of two dimension array.

2. Here from 6X7=42 elements, only 10 are non-zero. A[1,3]=6, A[1,5]=9, A[2,1]=2,
A[2,4]=7, A[2,5]=8, A[2,7]=4, A[3,1]=10, A[4,3]=12, A[6,4]=3, A[6,7]=5.

 One basic method for storing such a sparse matrix is to store non-zero elements in one
dimensional array and to identify each array elements with row and column indices fig
(c).

You might also like