Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

2 - Array Notes Proper

All Array problem in this pdf

Uploaded by

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

2 - Array Notes Proper

All Array problem in this pdf

Uploaded by

Sudhir Kindarley
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Array

Arrays in Java
Definition
An array is a collection of elements of the same type stored in a contiguous
memory location. It allows storing multiple values in a single variable, which
makes it easy to access and manipulate the data.

Key Characteristics
1. Fixed Size: The size of the array is defined when it's created and cannot be
changed.

2. Index-Based: Elements are accessed via an index starting from 0.

3. Homogeneous: All elements must be of the same data type.

4. Contiguous Memory Location

1. Array Declaration and Initialization


Syntax:

dataType[] arrayName; // Declaration


arrayName = new dataType[size]; // Initialization

Example:

int[] numbers = new int[5]; // Declares an array of 5 integer


s
String[] names = {"Alice", "Bob", "Charlie"}; // Initializes
with specific values

Array 1
2. Types of Arrays
1. Single-Dimensional Arrays: A list-like structure.

int[] scores = {90, 85, 75, 88, 92};

2. Multi-Dimensional Arrays: Arrays containing arrays; commonly used for


matrices.

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

3. Accessing and Modifying Elements


Accessing Elements:

int firstNumber = numbers[0]; // Accesses the first element


System.out.println(names[1]); // Outputs "Bob"

Modifying Elements:

numbers[2] = 50; // Sets the third element to 50

4. Length of an Array

Array 2
You can get the size of an array using .length :

int size = numbers.length; // Returns 5

5. Traversing Arrays
Using For Loop:

for (int i = 0; i < numbers.length; i++) {


System.out.println(numbers[i]);
}

Using Enhanced For Loop:

for (int score : scores) {


System.out.println(score);
}

How Arrays Use Contiguous Memory


When you declare an array in programming (like in Java), the computer allocates a
continuous block of memory that is large enough to hold all the elements of the
array.

Example:

int[] arr = new int[5];

This line tells the computer to:

Array 3
1. Allocate a block of memory that can store 5 integers.

2. Each integer typically takes 4 bytes , so the computer allocates 5 x 4 = 20 bytes

of contiguous memory space.

Memory Address Calculation in Arrays


Each element in the array is stored in a sequential, ordered memory location. If
you know the starting address (base address) of the array, you can calculate the
address of any element directly.

Memory Address Formula:

Address of arr[i] = Base Address + (i * size_of_each_element)

i : Index of the element you want to access.

size_of_each_element : Size of each array element (e.g., 4 bytes for an int ).

Example:
Suppose:

The base address of the array arr is 1000 .

Each integer takes 4 bytes .

Memory layout:

Index ( i ) Value ( arr[i] ) Memory Address


0 10 1000

1 20 1004

2 30 1008

3 40 1012

4 50 1016

To access arr[3] :

Address = 1000 + (3 * 4) = 1012

Array 4
The value stored at address 1012 is 40 .

3. Benefits of Using Contiguous Memory with Arrays


1. Efficient Index-Based Access (O(1) Time Complexity):

Since each element is stored sequentially, you can calculate the exact
memory address of any element using the formula above. This means you
can access any element directly without needing to traverse the array,
resulting in very fast ( O(1) ) access times.

Example: If you need the 5th element, you don't have to start from the
beginning and count each element; you can jump straight to the calculated
address.

2. Optimized for Cache Performance:

When data is stored contiguously, the CPU can load multiple elements into
the cache at once. This is because modern processors read data in
chunks (called cache lines). If elements are placed next to each other,
accessing one will likely load nearby elements, speeding up operations
like loops.

3. Easier to Manage Memory:

When you know that all elements are stored together, it simplifies the
process of managing memory, as you can treat the whole array as a single
block of memory.

Example of Contiguous Memory with Java Arrays


Let's write a Java program that demonstrates the concept:

public class ContiguousMemoryDemo {


public static void main(String[] args) {
// Declare and initialize an array
int[] arr = {10, 20, 30, 40, 50};

// Access elements using index


System.out.println("Element at index 0: " + arr[0]);

Array 5
// 10
System.out.println("Element at index 3: " + arr[3]);
// 40

// Simulating how we would calculate the address if w


e had access to memory addresses
int baseAddress = 1000; // Assume base address is 100
0
int elementSize = 4; // Each int is 4 bytes

// Calculate address of arr[3]


int addressOfElement3 = baseAddress + (3 * elementSiz
e);
System.out.println("Calculated address of arr[3]: " +
addressOfElement3);
}
}

Output:

Element at index 0: 10
Element at index 3: 40
Calculated address of arr[3]: 1012

Comparison with Non-Contiguous Data Structures


In contrast, data structures like Linked Lists do not use contiguous memory. Each
element (node) in a linked list can be anywhere in memory. The elements are
connected via pointers, which store the address of the next element.

Advantage of Linked List: You can easily grow or shrink the structure without
worrying about memory constraints, as each element is independently
allocated.

Array 6
Disadvantage of Linked List: Accessing elements is slower ( O(n) ) because
you have to traverse through each element from the start to reach the desired
position.

6. Common Array Operations

1. Array Copying:

int[] copy = Arrays.copyOf(numbers, numbers.length);

2. Array Sorting:

Arrays.sort(numbers); // Sorts the array in ascending orde


r

3. Searching an Element:

int index = Arrays.binarySearch(numbers, 75); // Finds the


index of 75

4. Filling an Array:

Arrays.fill(numbers, 100); // Sets all elements to 100

7. Multi-Dimensional Arrays
Declaration:

Array 7
int[][] matrix = new int[3][3]; // 3x3 matrix

Accessing Elements:

matrix[0][0] = 1; // Sets the element at the first row and co


lumn to 1
int value = matrix[1][2]; // Accesses the element at second r
ow, third column

Example:

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

8. Example Programs
1. Sum of Array Elements:

public class ArraySum {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;

for (int number : numbers) {


sum += number;
}

Array 8
System.out.println("Sum of array elements: " + su
m);
}
}

2. Find Maximum Element in an Array:

ublic class FindMax {


public static void main(String[] args) {
int[] scores = {90, 78, 85, 92, 88};
int max = scores[0];

for (int score : scores) {


if (score > max) {
max = score;
}
}

System.out.println("Maximum score: " + max);


}
}

3. Transpose of a Matrix:

public class TransposeMatrix {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Array 9
int[][] transpose = new int[3][3];

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];
}
}

// Print Transpose
for (int i = 0; i < transpose.length; i++) {
for (int j = 0; j < transpose[i].length; j++)
{
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}

9. Advantages and Disadvantages


Advantages:

Simple and easy to use.

Efficient for storing and accessing data by index.

Disadvantages:

Fixed size, making it inflexible when the number of elements is unknown.

Inefficient for insertion and deletion (as elements may need to be shifted).

10. Summary
Arrays are fundamental, fixed-size data structures.

They store elements of the same type.

Array 10
You can efficiently access and modify elements using their index.

Java provides the Arrays class for operations like sorting, searching, and
copying.

Practice Problems
1. Write a program to reverse an array.

2. Create a 2D array to store the marks of 5 students in 3 subjects and calculate


the average marks for each student.

3. Find the second largest element in an array without sorting it.

These notes cover the essential concepts and provide practical examples to help
you understand how to work with arrays in Java. Let me know if you'd like to go
deeper into any specific aspect!

Array Operations using ADT

In Java, you can implement array operations using the concept of Abstract Data
Types (ADT). An ADT defines a data structure conceptually, including the
operations that can be performed on it, without specifying how those operations
are implemented.
Let's consider an Array ADT and define operations that you might need to
perform, such as insertion, deletion, searching, and traversal. We'll implement
these operations using Java.

Array ADT Operations


An Array ADT typically supports the following operations:

1. Insert: Add an element to the array.

2. Delete: Remove an element from the array.

3. Search: Find the index of an element in the array.

4. Update: Change the value of an element at a specific index.

5. Traversal: Visit all elements of the array.

Array 11
Implementation of Array ADT in Java
Let's implement an ArrayADT class that encapsulates these operations:

java
Copy code
public class ArrayADT {
private int[] arr;
private int size;
private int capacity;

// Constructor to initialize the array


public ArrayADT(int capacity) {
this.capacity = capacity;
this.arr = new int[capacity];
this.size = 0;
}

// 1. Insert operation: Add an element to the array


public void insert(int element) {
if (size == capacity) {
System.out.println("Array is full, cannot insert
more elements.");
return;
}
arr[size] = element;
size++;
}

// 2. Delete operation: Remove an element at a given inde


x
public void delete(int index) {
if (index < 0 || index >= size) {
System.out.println("Invalid index. Cannot delet
e.");
return;

Array 12
}
// Shift elements to the left
for (int i = index; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
size--; // Reduce the size
}

// 3. Search operation: Return the index of the first occ


urrence of the element
public int search(int element) {
for (int i = 0; i < size; i++) {
if (arr[i] == element) {
return i;
}
}
return -1; // Return -1 if the element is not found
}

// 4. Update operation: Update the element at a specific


index
public void update(int index, int newValue) {
if (index < 0 || index >= size) {
System.out.println("Invalid index. Cannot updat
e.");
return;
}
arr[index] = newValue;
}

// 5. Traversal operation: Print all elements of the arra


y
public void traverse() {
if (size == 0) {
System.out.println("Array is empty.");
return;

Array 13
}
for (int i = 0; i < size; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}

// Getter for the size of the array


public int getSize() {
return size;
}

// Getter for the capacity of the array


public int getCapacity() {
return capacity;
}

public static void main(String[] args) {


// Create an Array ADT with a capacity of 10
ArrayADT array = new ArrayADT(10);

// Inserting elements
array.insert(5);
array.insert(10);
array.insert(15);
array.insert(20);

// Traversing array
System.out.print("Array elements: ");
array.traverse();

// Searching for an element


int index = array.search(15);
System.out.println("Element 15 found at index: " + in
dex);

Array 14
// Updating an element
array.update(2, 25); // Update the element at index 2
System.out.print("After updating index 2: ");
array.traverse();

// Deleting an element
array.delete(1); // Delete the element at index 1
System.out.print("After deleting index 1: ");
array.traverse();
}
}

Explanation of Each Operation


1. Insert Operation:

Adds an element at the end of the array.

Checks if the array has reached its capacity before adding a new element.

2. Delete Operation:

Removes an element from the array based on its index.

Shifts all elements after the specified index to the left to fill the gap.

Decreases the size of the array.

3. Search Operation:

Iterates through the array to find the index of the first occurrence of the
given element.

Returns 1 if the element is not found.

4. Update Operation:

Changes the value of the element at the specified index.

5. Traversal Operation:

Prints all the elements in the array.

Array 15
Useful for checking the current state of the array.

Output of the Program


When you run the main method, you should see output similar to this:

Array elements: 5 10 15 20
Element 15 found at index: 2
After updating index 2: 5 10 25 20
After deleting index 1: 5 25 20

Advantages of Using an Array ADT


1. Encapsulation: By using an ArrayADT class, you encapsulate all the array-
related operations, making the code cleaner and more organized.

2. Reusability: You can reuse this ArrayADT class in different parts of your
program without rewriting the same logic.

3. Abstraction: Users of the ArrayADT don't need to know how these operations
are implemented; they just need to know how to use them.

Conclusion
The Array ADT example in Java demonstrates how to manage array-based
operations such as insertion, deletion, search, update, and traversal. This way of
encapsulating functionality follows the principles of object-oriented
programming (OOP), where you can easily manage and manipulate arrays
through defined methods.
Feel free to modify or extend this class to add more operations, such as sorting,
reversing, or resizing the array. Let me know if you need more features or
explanations!

Array 16

You might also like