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

Arrays

The document discusses different types of array data structures including static arrays, fixed stack-dynamic arrays, stack-dynamic arrays, fixed heap-dynamic arrays, and heap-dynamic arrays. It describes the binding of subscript ranges and storage allocation for each type and their advantages and disadvantages.

Uploaded by

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

Arrays

The document discusses different types of array data structures including static arrays, fixed stack-dynamic arrays, stack-dynamic arrays, fixed heap-dynamic arrays, and heap-dynamic arrays. It describes the binding of subscript ranges and storage allocation for each type and their advantages and disadvantages.

Uploaded by

alukapellyvijaya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Array, Associative Arrays, Record, Union, Tuple Types, List Types

Array Types:
 An array is a homogeneous aggregate of data elements in which an individual element is
identified by its position in the aggregate, relative to the first element.
 The individual data elements of an array are of the same type.
 References to individual array elements are specified using subscript expressions.

Arrays and Indices

– Specific elements of an array are referenced by means of a two-level syntactic


mechanism, where the first part is the aggregate name, and the second part is a possibly
dynamic selector consisting of one or more items known as subscripts or indices.

– If all of the subscripts in a reference are constants, the selector is static;


otherwise, it is dynamic. The selection operation can be thought of as a mapping from
the array name and the set of subscript values to an element in the aggregate. Indeed,
arrays are sometimes called finite mappings. Symbolically, this mapping can be shown
as

array_name(subscript_value_list) → element
Subscript Bindings and Array Categories

– The binding of the subscript type to an array variable is usually static, but the
subscript value ranges are sometimes dynamically bound.
integer num_students = get_num_students(); // Assume this function returns the
number of students enrolled

string students[num_students]; // Declare an array with a size based on the


number of students

for integer i = 0 to num_students - 1 do


students[i] = get_student_name(i); // Assume this function returns the name of the
student at index i

 The binding of the subscript type (integer) to the students array variable is static. This
means that the indices used to access elements of the array must be of type integer and
this is determined at compile time.
 However, the range of valid indices (0 to num_students - 1) is dynamically bound
based on the number of students enrolled in the class. The size of the array and the
valid indices are determined during runtime based on the value returned by the
get_num_students() function.
So, while the type of subscripts (integer) remains static, the range of valid indices
is dynamically determined based on runtime information.

– There are five categories of arrays, based on the binding to subscript ranges, the
binding to storage, and from where the storage is allocated.

– A static array is one in which the subscript ranges are statically bound and storage
allocation is static (done before run time).

#include <stdio.h>

#define ARRAY_SIZE 5

int main() {
// Declare a static array of integers with a fixed size
int staticArray[ARRAY_SIZE];

// Assign values to the elements of the array


staticArray[0] = 10;
staticArray[1] = 20;
staticArray[2] = 30;
staticArray[3] = 40;
staticArray[4] = 50;

// Access and print the elements of the array


for (int i = 0; i < ARRAY_SIZE; i++) {
printf("staticArray[%d] = %d\n", i, staticArray[i]);
}

return 0;
}
 The staticArray is declared with a fixed size of ARRAY_SIZE, which is defined as 5.
 The subscript ranges (from 0 to ARRAY_SIZE - 1) are statically bound because they are
determined at compile time based on the constant value of ARRAY_SIZE.
 The storage allocation for the staticArray is static and done before runtime. Memory for
all elements of the array is allocated at compile time, and it remains fixed throughout the
execution of the program.
 Values are assigned to the elements of the array (staticArray) at runtime.
 The array is accessed and its elements are printed using a loop from 0 to ARRAY_SIZE -
1.

 The advantage of static arrays is efficiency: No dynamic


allocation or deallocation is required.

 The disadvantage is that the storage for the array is fixed for the entire
execution time of the program.

– A fixed stack-dynamic array is one in which the subscript ranges are statically
bound, but the allocation is done at declaration elaboration time during execution.
function processArray()
integer size
input size // get the size of the array from user input

// Declare a stack-dynamic array of integers with a size determined at runtime


integer stackDynamicArray[size]

// Populate the array with user input


for integer i = 0 to size - 1 do
input stackDynamicArray[i]

// Display the elements of the array


for integer i = 0 to size - 1 do
output stackDynamicArray[i]
 The size variable determines the size of the array, and it is obtained from user input
during runtime.
 The subscript ranges (0 to size - 1) are statically bound because they are determined at
compile time based on the size variable.
 However, the memory allocation for the array (stackDynamicArray) is done at
declaration elaboration time during execution, typically on the program's runtime
stack. This means the memory for the array is allocated dynamically during program
execution based on the value of size.
 The array stackDynamicArray behaves like a fixed-size array with dynamically
determined size, making it stack-dynamic.

 The advantage of fixed stack-dynamic arrays over static arrays


is space efficiency

 The disadvantage is the required allocation and deallocation time

– A stack-dynamic array is one in which both the subscript ranges and the storage
allocation are dynamically bound at elaboration time. Once the subscript ranges are
bound and the storage is allocated, however, they remain fixed during the lifetime of
the variable.
Example:

def create_stack_dynamic_array(size):

# Dynamically allocate memory for the array based on the given size

stack_dynamic_array = [None] * size

return stack_dynamic_array

def main():

# Get the size of the array from user input

size = int(input("Enter the size of the stack-dynamic array: "))

# Create a stack-dynamic array

stack_dynamic_array = create_stack_dynamic_array(size)
# Populate the array with user input

for i in range(size):

stack_dynamic_array[i] = int(input(f"Enter element at index {i}: "))

# Display the elements of the array

print("Elements of the stack-dynamic array:")

for i in range(size):

print(f"stack_dynamic_array[{i}] = {stack_dynamic_array[i]}")

if __name__ == "__main__":

main()

 The function create_stack_dynamic_array() dynamically allocates memory for the array


based on the given size. The subscript ranges and storage allocation are both dynamically
bound at elaboration time when this function is called.
 Once the array is created and the memory is allocated, the subscript ranges and storage
allocation remain fixed during the lifetime of the stack_dynamic_array variable.

 The advantage of stack-dynamic arrays over static and fixed stack-


dynamic arrays is flexibility

– A fixed heap-dynamic array is similar to a fixed stack-dynamic array, in that the


subscript ranges and the storage binding are both fixed after storage is allocated.
– In a fixed heap-dynamic array, like in a fixed stack-dynamic array, the subscript
ranges and storage binding are both fixed after storage is allocated.
– However, unlike a stack-dynamic array where memory is typically allocated on the
program's runtime stack, in a heap-dynamic array, memory is allocated on the heap,
which allows for more flexibility in size and lifetime.

 The advantage of fixed heap-dynamic arrays is flexibility—the


array‘s size always fits the problem.

 The disadvantage is allocation time from the heap, which is


longer than allocation time from the stack.

• A heap-dynamic array is one in which the binding of subscript ranges and storage
allocation is dynamic and can change any number of times during the array‘s
lifetime.
• In a heap-dynamic array, the binding of subscript ranges and storage allocation is
dynamic, meaning they can change any number of times during the array's lifetime.
• This flexibility allows for resizing the array as needed. An example of a heap-
dynamic array can be found in languages such as Python, where arrays can be
dynamically resized using the list type.

– The advantage of heap-dynamic arrays over the others is flexibility:

– The disadvantage is that allocation and deallocation take longer and


may happen many times during execution of the program.

Array Initialization

Some languages provide the means to initialize arrays at the time their storage is
allocated. An array aggregate for a single-dimensioned array is a list of literals
delimited by parentheses and slashes. For example, we could have

Integer, Dimension (3) :: List = (/0, 5,5/)


In the C declaration

int list [] = {4, 5, 7, 83};

These arrays can be initialized to string constants, as in


char name [] = "freddie";

Arrays of strings in C and C++ can also be initialized with string literals. In this
case, the array is one of pointers to characters.

For example,

char *names [] = {"Bob", "Jake" ,"Darcie"};

In Java, similar syntax is used to define and initialize an array of references to String
objects. For example,

String[] names = ["Bob", "Jake", "Darcie"];


Ada provides two mechanisms for initializing arrays in the declaration statement:
Listing elements in order: In this approach, you simply list the elements of the array in
the order they should be stored. Ada arrays are indexed starting from 1 by default. For
example:

List : array (1..5) of Integer := (1, 3, 5, 7, 9);


In this declaration, an array named List of type Integer with indices ranging from 1 to 5 is
created, and it is initialized with the values 1, 3, 5, 7, and 9 respectively.
Using the arrow operator (=>): This approach allows you to specify values for specific indices
within the array using the arrow operator. You can directly assign values to specific index
positions while initializing the array, and use the others keyword to assign a default value to all
other indices. For example:
Bunch : array (1..5) of Integer := (1 => 17, 3 => 34, others => 0);
In this declaration, an array named Bunch of type Integer with indices ranging from 1 to 5 is
created. The values 17 and 34 are assigned to indices 1 and 3 respectively, while the others
keyword assigns 0 to all other indices.

Rectangular and Jagged Arrays:


Rectangular Array: In a rectangular array, all rows have the same number of elements and
all columns have the same number of elements. This creates a uniform grid-like structure.

Rectangular Array:myArray[3][7]

In this example, myArray is a 2D array with 3 rows and 7 columns. All rows have the same
length (7 elements) and all columns have the same length (3 elements). This creates a grid
where each row is the same length and each column is the same height.

In this example, myArray is a 2D array with 3 rows and 7 columns. All rows have the same
length (7 elements) and all columns have the same length (3 elements). This creates a grid
where each row is the same length and each column is the same height.

//Declaration and initialization of a rectangular array in Ada

type Rectangular_Array is array(1..3, 1..7) of Integer;

MyArray : Rectangular_Array :=

((1, 2, 3, 4, 5, 6, 7),

(8, 9, 10, 11, 12, 13, 14),

(15, 16, 17, 18, 19, 20, 21));


In this Ada example, MyArray is a rectangular 2D array with 3 rows and 7 columns, where each
row has the same number of elements (7 in this case).

Jagged Array: In a jagged array, the lengths of rows need not be the same. This means
that different rows can have different numbers of elements.

Jagged Array:

myJaggedArray[3][] = {

{1, 2},

{3, 4, 5},

{6, 7, 8, 9}

In this example, myJaggedArray is a 2D jagged array with 3 rows. The first row has 2 elements,
the second row has 3 elements, and the third row has 4 elements.
Declaration and initialization of a jagged array in Ada
type Jagged_Array is array(1..3) of Array_of_Integers;
type Array_of_Integers is array(Integer range <>) of Integer;

MyJaggedArray : Jagged_Array :=
((1, 2),
(3, 4, 5),
(6, 7, 8, 9));

In this Ada example, MyJaggedArray is a jagged 2D array with 3 rows. Each row is represented
as an array of integers, and the lengths of these arrays can vary, allowing for different numbers
of elements in each row.

Slices:

A slice of an array is some substructure of that array.

For example, if A is a matrix, then the first row of A is one possible slice, as are
the last row and the first column. It is important to realize that a slice is not a new data
type. Rather ,it is a mechanism for referencing part of an array as a unit.

Consider an example of a 2D array (matrix) in Ada:

type Matrix is array(1..3, 1..3) of Integer;


A : Matrix := ((1, 2, 3),
(4, 5, 6),
(7, 8, 9));
First Row Slice: A slice representing the first row of the matrix. It includes all
elements of the first row.
Row1_Slice : Matrix(1..1, 1..3) := A(1..1, 1..3);
Row1_Slice references the first row of the matrix A.
Last Row Slice: A slice representing the last row of the matrix. It includes all
elements of the last row.
Last_Row_Slice : Matrix(3..3, 1..3) := A(3..3, 1..3);
Last_Row_Slice references the last row of the matrix A.
First Column Slice: A slice representing the first column of the matrix. It
includes all elements of the first column.
Column1_Slice : Matrix(1..3, 1..1) := A(1..3, 1..1);
Column1_Slice references the first column of the matrix A.
Slices allow us to work with these portions of the array as if they were
standalone entities, enabling operations like modifications, calculations, or passing to
functions.
Evaluation

Arrays have been included in virtually all programming languages

Implementation of Array Types

Implementing arrays requires considerably more compile-time effort than does


implementing primitive types. The code to allow accessing of array elements must be
generated at compile time. At run time, this code must be executed to produce element
addresses. There is no way to pre compute the address to be accessed by a reference
such as list [k]

A single-dimensioned array is implemented as a list of adjacent memory cells.


Suppose the array list is defined to have a subscript range lower bound of 0. The access
function for list is often of the form address ( list [k] ) = address (list [0] ) + k *
element_size where the first operand of the addition is the constant part of the access
function, and the second is the variable part .

If the element type is statically bound and the array is statically bound to
storage, then the value of the constant part can be computed before run time. However,
the addition and multiplication operations must be done at run time.
The generalization of this access function for an arbitrary lower bound is
address (list[k]) = address ( list [lower_bound]) + ( (k - lower_bound) *
element_size)

Suppose we have an array named List with a lower bound of 1, and we want to access the
element at index k. The access function can be generalized as:

address(list[k]) = address(list[lower_bound]) + ((k - lower_bound) * element_size)

Where:
 address(list[k]) is the memory address of the element at index k.
 address(list[lower_bound]) is the memory address of the element at the lower bound of
the array.
 element_size is the size of each element in memory (in bytes).
 k is the index we want to access.
 lower_bound is the lower bound of the array.

Example in Ada:

type Integer_Array is array(1..5) of Integer; -- Lower bound is 1

List : Integer_Array := (10, 20, 30, 40, 50);

Suppose we want to access List(3). Using the access function, we can calculate its memory
address as follows:

address(List[3]) = address(List[1]) + ((3 - 1) * sizeof(Integer))


Assuming address(List[1]) is 0x1000 and sizeof(Integer) is 4 bytes (for example), the calculation
would be:

address(List[3]) = 0x1000 + ((3 - 1) * 4)

= 0x1000 + (2 * 4)

= 0x1000 + 8

= 0x1008

So, the memory address of List(3) would be 0x1008

Associative Arrays

 An associative array is an unordered collection of data elements that


are indexed by an equal number of values called keys.
 In the case of non-associative arrays, the indices never need to be stored
(because of their regularity). In an associative array, however, the user-
defined keys must be stored in the structure. So each element of an
associative array is in fact a pair of entities, a key and a value.
 We use Perl‘s design of associative arrays to illustrate this data
structure.
 Associative arrays are also supported directly by Python, Ruby, and Lua
and by the standard class libraries of Java, C++, C#, and F#.
 The only design issue that is specific for associative arrays is the form
of references to their elements.

Structure and Operations

 In Perl, associative arrays are called hashes, because in the


implementation their elements are stored and retrieved with hash
functions.
 The namespace for Perl hashes is distinct: Every hash variable name
must begin with a percent sign (%).
 Each hash element consists of two parts: a key, which is a string, and a
value, which is a scalar (number, string, or reference).
 Hashes can be set to literal values with the assignment statement, as in

%salaries = ("Gary" => 75000, "Perry" => 57000, "Mary" => 55750, "Cedric" =>
47850); Recall that scalar variable names begin with dollar signs ($). For
example,
$salaries {"Perry"} = 58850;

A new element is added using the same assignment statement form. An element
can be removed from the hash with the delete operator, as in

Delete $salaries{"Gary"};

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy