[Go to site: main page, start]

100% found this document useful (1 vote)
370 views8 pages

Java Array Operations Guide

The document contains code and instructions for a lab session on data structures and algorithms. It includes Java code to read array elements, insert an element at a given position within the array, insert an element at the beginning of the array, and insert an element at the end of the array. The code examples demonstrate how to traverse arrays, shift existing elements, and insert new elements in various positions within the array.

Uploaded by

Rohini Aravindan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
370 views8 pages

Java Array Operations Guide

The document contains code and instructions for a lab session on data structures and algorithms. It includes Java code to read array elements, insert an element at a given position within the array, insert an element at the beginning of the array, and insert an element at the end of the array. The code examples demonstrate how to traverse arrays, shift existing elements, and insert new elements in various positions within the array.

Uploaded by

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

PRESIDENCY UNIVERSITY

Bengaluru, Karnataka
Computer Science & Engineering
School of Computer Science & Engineering

Subject: CSE2001 - Data Structures & Algorithms Semester: III


Lab Session 2: Date: 06/09/2023

1. Java code to read and print array elements:(Array Traversal, Insert at


beginning, Insert at given position, Insert at end)
import [Link].*;
public class read_array
{
public static void main(String args[ ])
{
Scanner sc=new Scanner([Link]);
int n, i; //variable n is used to store size of array, variable i is used indexing
int a[]=new int[10]; // array declaration in java language
[Link](“Enter the size of array”);
n=[Link]();
[Link](“Enter the array elements”);
for(i=0;i<n;i++)
{
a[i]=[Link]();
}
[Link](“The array elements are:”);
for(i=0;i<n;i++)
{
[Link](a[i]);
}
}
}

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 1
Output:

Note: Memory allocation after reading array elements will be as follows:


a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

1 2 3 4 5 0 0 0 0 0

➔ The unused array elements are filled with value 0

2. Inserting element in an array for given position:


Assume value 60 should be inserted at position 3(index value =2) as shown in below table

10 20 30 40 50
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

pos=3, value=60 (current value of i=4 after adding 5 elements in array)


Add the below code snippet in previous java code:
int pos, value;
[Link]("Enter the position to insert new element");
pos=[Link]();
[Link]("Enter the value");
value=[Link]();
for(i=n-1;i>=pos-1;i--)
{
a[i+1]=a[i];
[Link](a[i+1]);
}
a[pos-1]=value;
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 2
n++;
[Link]("The array elements are inserting new element is:");
for(i=0;i<n;i++)
{
[Link](a[i]);
}

After adding this code in main program the resultant final code for array traversal and
inserting element at given position is:
import [Link].*;
public class read_array
{
public static void main(String args[ ])
{
Scanner sc=new Scanner([Link]);
int n, i; //variable n is used to store size of array, variable i is used indexing
int a[]=new int[10]; // array declaration in java language
int pos, value;
[Link]("Enter the size of array");
n=[Link]();
[Link]("Enter the array elements");
for(i=0;i<n;i++)
{
a[i]=[Link]();
}
[Link]("The array elements are:");
for(i=0;i<n;i++)
{
[Link](a[i]);
}
[Link]("Enter the position to insert new element");

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 3
pos=[Link]();
[Link]("Enter the value");
value=[Link]();
for(i=n-1;i>=pos-1;i--)
{
a[i+1]=a[i];
}
a[pos-1]=value;
n++;
[Link]("The array elements are inserting new element is:");
for(i=0;i<n;i++)
{
[Link](a[i]);
}

}
}
Output:

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 4
Logic:
1. Push existing element at position 5 (index value=4) to position 6 (index value=5)

10 20 30 40 50
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

2. Push existing element at position 4 (index value=3) to position 5 (index value=4)

10 20 30 40 50
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

3. Push existing element at position 3 (index value=2) to position 4 (index value=3)

10 20 30 40 50
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

3. Write a Java code to insert element at beginning in array:


Note: Just change one condition in the above final code to insert element at beginning

for(i=n-1;i>=0;i--)

a[i+1]=a[i];

The final code is:

import [Link].*;
public class read_array
{
public static void main(String args[ ])
{
Scanner sc=new Scanner([Link]);
int n, i; //variable n is used to store size of array, variable i is used indexing
int a[]=new int[10]; // array declaration in java language
int pos, value;
[Link]("Enter the size of array");
n=[Link]();
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 5
[Link]("Enter the array elements");
for(i=0;i<n;i++)
{
a[i]=[Link]();
}
[Link]("The array elements are:");
for(i=0;i<n;i++)
{
[Link](a[i]);
}
[Link]("Enter the position to insert new element");
pos=[Link]();
[Link]("Enter the value");
value=[Link]();
for(i=n-1;i>=0;i--) //Only the highlighted condition is changed
{
a[i+1]=a[i];
}
a[pos-1]=value;
n++;
[Link]("The array elements are inserting new element is:");
for(i=0;i<n;i++)
{
[Link](a[i]);
}

}
}

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 6
Output:

4. Write a Java code to insert element at the end in an array:


import [Link].*;
public class read_array
{
public static void main(String args[ ])
{
Scanner sc=new Scanner([Link]);
int n, i; //variable n is used to store size of array, variable i is used indexing
int a[]=new int[10]; // array declaration in java language
int value;
[Link]("Enter the size of array");
n=[Link]();
[Link]("Enter the array elements");
for(i=0;i<n;i++)
{
a[i]=[Link]();

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 7
}
[Link]("The array elements are:");
for(i=0;i<n;i++)
{
[Link](a[i]);
}
[Link]("Enter the value");
value=[Link]();
a[i]=value;
n++;
[Link]("The array elements are inserting new element is:");
for(i=0;i<n;i++)
{
[Link](a[i]);
}

}
}
Output:

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 8

Common questions

Powered by AI

Inserting an element at the end of an array in Java is less complex than inserting at a specified position because it does not require shifting any existing elements. You simply append the new element after the last element and increment the size by one. In contrast, inserting at a specified position involves shifting elements from that position onwards to create space for the new element, making it more computationally intensive as the number of shifts depends on the position of insertion .

The insertion of an element changes the logical size by increasing the count of elements actively considered as part of the array, even though the physical size remains constant unless specifically reallocated. Arrays have a fixed physical size due to initial declaration, which does not change unless explicitly resized, while the logical size increases to reflect additions within the available physical capacity, enhancing array operations without additional memory allocation .

Using a fixed-size array for data storage in Java presents computational implications, notably during insertion operations, since these often require shifting elements. This operation inherently has a time complexity of O(n), where n is the number of elements being shifted, thus possibly resulting in high computation costs as the array grows. Furthermore, fixed-size constraints mean careful planning for maximum array utilization is crucial to avoid inefficiencies or costly array resizing operations when maximum capacity is approached or exceeded .

Cursor management in Java arrays, often realized by maintaining a variable that tracks the current size (logical cursor position), aids efficiency by distinguishing between used and unused portions of the array. This management helps streamline operations such as insertions and traversals, as the operations are confined to elements up to the cursor position, avoiding unnecessary checks or changes to the undefined regions of the array. This practice optimizes functionality and maintains data integrity through precise control over where operations are applicable .

When inserting a new element at the beginning of a Java array, memory allocation changes as follows: 1. Identify the current array's filled length (`n`). 2. Begin a loop from position `n-1` (last filled position) down to `0`, incrementing each element index by 1 to shift all elements to the right. 3. After all elements have been shifted, set the first position (index 0) of the array to the new value. 4. Increment the array's filled length (`n++`). Memory allocation remains unchanged, but the order and positions of elements are affected .

The logic for shifting elements in a Java array involves iterating backwards from the last filled position to the target insertion position and assigning each element to the index immediately following its current index. The backward iteration is crucial because it prevents overwriting values before they have been moved, ensuring that all existing data is preserved and shifted accurately. This backward logic supports orderly and predictable results for element repositioning .

To insert a new element at a specified position in an array in Java, a sequence of shifts must be performed to make space for the new element. First, the current elements starting from the last until the position where the insertion is needed must be shifted one position to the right, creating a vacancy at the desired position. For example, to insert an element at position 3 (index value 2), the loop moves elements from the end of the filled portion of the array to the right until the target position is available. Then, the new element can be inserted at the specified position .

Changing the loop condition helps manage where the insertion begins. For inserting at the beginning of an array, the condition in the shifting loop changes from `for(i=n-1;i>=pos-1;i--)` to `for(i=n-1;i>=0;i--)`, enabling all elements to be shifted one position to the right, starting from the last element down to the zero index. This shift creates a space at the array's front where the new element is inserted .

Array size limitation directly impacts insertion operations because an array in Java has to be declared with a fixed size, and any insertion operation cannot exceed this predefined size. If you attempt to insert beyond the allocated space, it will result in an array index out of bounds error. Therefore, careful management of the array's current size and reserved capacity is necessary to successfully conduct insertions, ensuring that you are operating within the array's bounds .

Java initializes unused elements in a newly declared fixed-size array with default values, typically zero for numerical data types. To better manage these unused elements, a strategy could involve dynamically managing the visible size of the array rather than relying entirely on the array's declared size. This strategy requires maintaining a separate variable for the array's current logical size, indicating how many elements are actively being used, which helps avoid processing or displaying unneeded default elements .

You might also like