[Go to site: main page, start]

0% found this document useful (0 votes)
8 views15 pages

Java Array Manipulation Techniques

The document contains multiple Java assignments that cover various programming concepts, including binary search, array manipulation (insertion and removal), finding pairs with a specific sum, matrix operations, a basic calculator, and operations on complex numbers. Each assignment includes a problem statement, source code, example output, and a discussion explaining the functionality and complexity of the code. The assignments demonstrate fundamental programming techniques and data structures in Java.
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
0% found this document useful (0 votes)
8 views15 pages

Java Array Manipulation Techniques

The document contains multiple Java assignments that cover various programming concepts, including binary search, array manipulation (insertion and removal), finding pairs with a specific sum, matrix operations, a basic calculator, and operations on complex numbers. Each assignment includes a problem statement, source code, example output, and a discussion explaining the functionality and complexity of the code. The assignments demonstrate fundamental programming techniques and data structures in Java.
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

Assignment – 1

Date: 15.05.2025
Problem Statement:
Write a Java program to implement binary search.
Source Code:
import [Link].*;
class Bin{
public static void main(String args[]){
Scanner sc=new Scanner([Link]);
[Link]("Enter the range of the array: ");
int n=[Link]();
int a[]=new int[n];
[Link]("Enter "+n+" elements: ");
for(int i=0;i<n;i++){
[Link](i+"th element: ");
a[i]=[Link]();
}
int t;
for(int i=0;i<n-1;i++){
for(int j=0;j<n-i-1;j++){
if(a[j] >a[j+1]){
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
[Link]("Enter the value to search in array: ");
int k=[Link]();
int m;
int f=0;
int l=n-1;
int flag=0;
while(f <= l){
m=(f+l)/2;
if(a[m] < k){
f=m+1;
}
else if(a[m] == k){
flag=1;
break;
}

1|Page
else if(a[m] > k){
l=m-1;
}
}
if(flag==1){
[Link](k+" is in the array.");
}
else{
[Link](k+" is not in the array.");
}
}
}

Output:
Enter the range of the array: 5
Enter 5 elements:
0th element: 67
1th element: 99
2th element: 76
3th element: 55
4th element: 23
Enter the value to search in array: 98
98 is not in the array.

Enter the range of the array: 5


Enter 5 elements:
0th element: 67
1th element: 99
2th element: 76
3th element: 55
4th element: 23
Enter the value to search in array: 23
23 is in the array.

Discussion:
The Java code allows users to input an array of integers, sorts it with Bubble Sort, and searches
for a value using Binary Search. It demonstrates basic data handling, with Bubble Sort having a
time complexity of \(O(n^2)\) and Binary Search \(O(\log n)\), ultimately informing the user if
the searched value exists in the array.

2|Page
Assignment – 2
Date: 26.05.2025
Problem Statement:
Write a Java program to insert an element at specific position of an array.

Source Code:
import [Link].*;
public class Insert {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int s = [Link]();
int[] array = new int[s + 1];
[Link]("Enter " + s + " elements of the array:");
for (int i = 0; i < s; i++) {
array[i] = [Link]();
}
[Link]("Enter the element to insert: ");
int element = [Link]();
[Link]("Enter the position (1 to " + (s + 1) + ") to insert the element:");
int pos = [Link]();
if (pos < 1 || pos > s + 1) {
[Link]("Invalid position!");
return;
}
for (int i = s; i >= pos; i--) {
array[i] = array[i - 1];
}
array[pos - 1] = element;
[Link]("Array after insertion:");
for (int i = 0; i <= s; i++) {
[Link](array[i] + " ");
}
}
}

Output:
Enter the size of the array: 5
Enter 5 elements of the array:
67 55 90 21 43
Enter the element to insert: 77
Enter the position (1 to 6) to insert the element:6
Array after insertion:
67 55 90 21 43 77

Enter the size of the array: 5


Enter 5 elements of the array:
67 55 90 21 43

3|Page
Enter the element to insert: 33
Enter the position (1 to 6) to insert the element:4
Array after insertion:
67 55 90 33 21 43
Discussion:
The provided Java code implements a program that allows users to insert an element into a
specific position in an array. It begins by prompting the user for the size of the array and its
elements, utilizing the Scanner class for input. The program then asks for the element to be
inserted and the desired position. It checks if the position is valid (between 1 and the size of the
array plus one) and, if valid, shifts the existing elements to the right to create space for the new
element. Finally, it inserts the element and displays the updated array. This code effectively
demonstrates basic array manipulation techniques in Java, including element insertion and
boundary checking.

4|Page
Assignment – 3
Date: 26.05.2025
Problem Statement:
Write a Java program to remove an element from specific position of an
array.

Source Code:
import [Link].*;
class Remove {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int s = [Link]();
int[] arr = new int[s];
[Link]("Enter " + s + " elements of the array:");
for (int i = 0; i < s; i++) {
arr[i] = [Link]();
}
[Link]("Enter the position (1 to " + s + ") of the element to remove: ");
int position = [Link]();
if (position < 1 || position > s) {
[Link]("Invalid position! Please run the program again.");
return;
}
for (int i = position - 1; i < s - 1; i++) {
arr[i] = arr[i + 1];
}
[Link]("Array after removal:");
for (int i = 0; i < s - 1; i++) {
[Link](arr[i] + " ");
}
}
}
Output:
Enter the size of the array: 5
Enter 5 elements of the array:
43 22 31 90 76
Enter the position (1 to 5) of the element to remove: 3
Array after removal:
43 22 90 76

5|Page
Discussion:
The provided Java code implements a program that allows users to remove an element from a
specified position in an array. It starts by prompting the user for the size of the array and its
elements, using the Scanner class for input. After reading the array, the program asks for the
position of the element to be removed and checks if the position is valid (between 1 and the
size of the array). If valid, it shifts the subsequent elements to the left to fill the gap created by
the removed element. Finally, it displays the updated array, demonstrating basic array
manipulation techniques in Java, including element removal and boundary checking.

6|Page
Assignment – 4
Date: 26.05.2025

Problem Statement:
Write a Java program to find all the pairs in an array whose sum is equal to
a specific number.

Source Code:
import [Link].*;
class Pair {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int n = [Link]();
while (n <= 0) {
[Link]("Enter a positive integer: ");
n = [Link]();
}
int[] arr = new int[n];
[Link]("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}
[Link]("Enter the target sum: ");
int target = [Link]();
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == target) {
[Link]("(" + arr[i] + ", " + arr[j] + ")");
count++;
}
}
}
}
}
Output:
Enter the size of the array: 10
Enter the elements of the array:
1 2 3 4 5 6 7 9 8 11

7|Page
Enter the target sum: 9
(1, 8)
(2, 7)
(3, 6)
(4, 5)
Discussion:
The provided Java code implements a program that finds and prints all unique pairs of
elements in an array that sum up to a specified target value. It begins by prompting the user for
the size of the array and ensures that the input is a positive integer. After reading the array
elements, the program asks for the target sum. It then uses a nested loop to check all possible
pairs of elements in the array, printing those that meet the target sum condition. This code
effectively demonstrates basic array manipulation and nested iteration in Java, showcasing how
to find pairs that satisfy a specific condition. However, the algorithm has a time complexity of
O(n^2), which may not be efficient for large arrays.

8|Page
Assignment – 5
Date: 26.05.2025
Problem Statement:
Write a Java program to print the row wise and column wise minimum
number in a matrix.

Source Code:
import [Link].*;
public class Matrix {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of rows: ");
int rows = [Link]();
[Link]("Enter the number of columns: ");
int cols = [Link]();
int[][] matrix = new int[rows][cols];
[Link]("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = [Link]();
}}
[Link]("Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](matrix[i][j] + "\t");
}
[Link]();
}
int[] row = new int[rows];
for (int i = 0; i < rows; i++) {
row[i] = matrix[i][0];
for (int j = 1; j < cols; j++) {
if (matrix[i][j] < row[i]) {
row[i] = matrix[i][j];
}}}
int[] col = new int[cols];
for (int j = 0; j < cols; j++) {
col[j] = matrix[0][j];
for (int i = 1; i < rows; i++) {
if (matrix[i][j] < col[j]) {
col[j] = matrix[i][j];
}}}

9|Page
[Link]("Matrix with Row Min and Column Min:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
[Link](matrix[i][j] + "\t");
}
[Link]("| Row " + (i+1) + " Min: " + row[i]);
[Link]();
}
[Link]("Column Min: ");
for (int j = 0; j < cols; j++) {
[Link](col[j] + "\t");
}
[Link]();
}
}

Output:
Enter the number of rows: 3
Enter the number of columns: 3
Enter the elements of the matrix:
23 4 5
984
261
Matrix:
23 4 5
9 8 4
2 6 1
Matrix with Row Min and Column Min:
23 4 5 | Row 1 Min: 4
9 8 4 | Row 2 Min: 4
2 6 1 | Row 3 Min: 1
Column Min: 2 4 1
Discussion:
The provided Java code implements a program that allows users to input a matrix of integers
and then calculates the minimum values for each row and each column. It starts by prompting
the user for the dimensions of the matrix and its elements, using the Scanner class for input.
After reading the matrix, the program prints it in a formatted manner. It then computes the
minimum value for each row and each column, storing these values in separate arrays. Finally,
it displays the matrix again, appending the minimum value of each row and printing the
minimum values of each column below the matrix. This code effectively demonstrates basic
matrix manipulation and iteration techniques in Java, showcasing how to work with 2D arrays
and perform calculations based on their contents.

10 | P a g e
Assignment – 6
Date: 09.06.2025
Problem Statement:
Write a Java program to implement a calculator.

Source Code:
import [Link].*;
class Calculator{
int f,s;
void add(){
int res=f+s;
[Link]("Summation is: "+res);
}
void sub(){
int res=f-s;
[Link]("Substraction is: "+res);
}
void mul(){
int res=f*s;
[Link]("Multiplication is: "+res);
}
void div(){
if(s==0){
[Link]("Error");
}
else{
int res =f/s;
[Link]("Division is: "+res);
}
}
public static void main(String args[]){
Scanner sc=new Scanner([Link]);
Calculator cal=new Calculator();
[Link]("Enter first value: ");
cal.f=[Link]();
[Link]("Enter second value: ");
cal.s=[Link]();
while(true){
[Link]("Enter the operator type(+.-.*./) or q to quit: ");
char op=[Link]().charAt(0);
switch(op){
case '+':

11 | P a g e
[Link]();
break;
case '-':
[Link]();
break;
case '*':
[Link]();
break;
case '/':
[Link]();
break;
case 'q':
[Link](0);
default:
[Link]("Error");
break;
}
}
}
}

Output:
Enter first value:
90
Enter second value:
55
Enter the operator type(+.-.*./) or q to quit:
+
Summation is: 145
Enter the operator type(+.-.*./) or q to quit:
-
Substraction is: 35
Enter the operator type(+.-.*./) or q to quit:
*
Multiplication is: 4950
Enter the operator type(+.-.*./) or q to quit:
/
Division is: 1
Enter the operator type(+.-.*./) or q to quit:
q

12 | P a g e
Discussion:
This Java code implements a basic calculator that performs addition, subtraction,
multiplication, and division operations. It utilizes a Calculator class with methods for each
operation and a main method that takes user input for numbers and operators. The program
runs in a loop, allowing users to perform multiple calculations until they choose to quit by
entering 'q'. Error handling is included for division by zero and invalid operators, ensuring a
robust user experience. Overall, the code demonstrates fundamental concepts of object-
oriented programming and user interaction in Java.

13 | P a g e
Assignment – 7
Date: 09.06.2025
Problem Statement:
Write a Java program to implement addition, subtraction, multiplication
for complex numbers.

Source Code:
import [Link].*;
class Complex {
double real;
double imag;
Complex(double real, double imag) {
[Link] = real;
[Link] = imag;
}
void add(Complex other) {
double resReal = [Link] + [Link];
double resImag = [Link] + [Link];
[Link]("Sum: " + resReal + " + " + resImag + "i");
}
void sub(Complex other) {
double resReal = [Link] - [Link];
double resImag = [Link] - [Link];
[Link]("Difference: " + resReal + " + " + resImag + "i");
}
void mul(Complex other) {
double resReal = [Link] * [Link] - [Link] * [Link];
double resImag = [Link] * [Link] + [Link] * [Link];
[Link]("Product: " + resReal + " + " + resImag + "i");
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first complex number (real imaginary): ");
Complex c1 = new Complex([Link](), [Link]());
[Link]("Enter second complex number (real imaginary): ");
Complex c2 = new Complex([Link](), [Link]());
while(true) {
[Link]("Enter operator (+, -, *) or q to quit: ");
char op = [Link]().charAt(0);
switch(op) {
case '+':
[Link](c2);

14 | P a g e
break;
case '-':
[Link](c2);
break;
case '*':
[Link](c2);
break;
case 'q':
[Link](0);
default:
[Link]("Invalid operator.");
}
}
}
}

Output:
Enter first complex number (real imaginary):
8 5
Enter second complex number (real imaginary):
7 3
Enter operator (+, -, *) or q to quit:
+
Sum: 15.0 + 8.0i
Enter operator (+, -, *) or q to quit:
-
Difference: 1.0 + 2.0i
Enter operator (+, -, *) or q to quit:
*
Product: 41.0 + 59.0i
Enter operator (+, -, *) or q to quit:
q
Discussion:
This Java code implements a complex number calculator, allowing users to perform addition,
subtraction, and multiplication operations on complex numbers through a Complex class. It's
well-structured and demonstrates object-oriented programming in Java.

15 | P a g e

Common questions

Powered by AI

Boundary checking ensures that insertions and removals occur within the valid index range of an array, preventing out-of-bounds exceptions that could crash programs. By affirming operations only proceed at valid positions, the program mitigates errors from improper accesses or manipulation, especially in operations requiring elements to move to adjacent indices. This checking helps in maintaining program stability, ensuring only intended locations are modified, and enhances data integrity by maintaining valid array states throughout operations .

Using the Scanner class in Java for user interface provides a straightforward way to handle user input through the command line. While this approach is suitable for simple applications and educational contexts due to ease of use, it may introduce performance bottlenecks when managing large volumes of input data interactively, owing to its synchronous nature—waiting for user input before proceeding. Additionally, UI interactivity is limited compared to graphical interfaces, offering less intuitive user experiences and lacking advanced features like real-time feedback or validation .

Finding row-wise and column-wise minimums involves iterating over each element of the matrix. The challenges include maintaining separate tracking for rows and columns, ensuring the solution handles varied matrix sizes, and achieving this with minimal extra space. The solution involves using separate arrays to track the minimum for rows and columns within nested loops. While this approach works well, optimizing for very large datasets can be challenging, as computational cost grows with the size of the matrix. Employing parallel processing or specialized libraries can mitigate performance issues for massive matrices .

Using a nested loop to find element pairs that sum to a target is straightforward and easy to implement, as it directly checks all possible pairs. However, its major drawback is inefficiency, with a time complexity of O(n^2), making it unsuitable for large arrays. An advantage is its simplicity in finding all combinations without additional data structures. However, using hash tables or sorting the array can significantly reduce computation time to O(n) or O(n log n) respectively, but at the expense of implementation complexity .

The main limitation of using bubble sort, which has O(n^2) complexity, before binary search is inefficiency, particularly with larger arrays. Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they're in the wrong order, which is performant for small datasets but slow for large ones. For better performance, quicker sorting algorithms like quicksort or mergesort, both with O(n log n) complexity, are preferable. This inadequacy in pre-sorting could negate the efficiency gained from binary search, making the combined process less efficient .

When inserting an element into a specific position, the array must shift all the subsequent elements one position to the right to make space, which can be costly in terms of time—O(n) in the worst case—but doesn't require extra memory for new nodes. In contrast, linked lists allow elements to be inserted at any position without shifting, but they require additional memory for storing pointers. Therefore, arrays are typically quicker if elements are inserted at the end, while linked lists are more efficient for frequent insertions and deletions at arbitrary positions .

Encapsulation in the complex number calculator is achieved by using a class to define complex numbers with associated operations. This design hides the implementation details (attributes and methods), exposing only necessary functionalities like addition, subtraction, and multiplication through an interface. It benefits the program by offering a modular structure that enhances maintainability, reusability, and ease of modification. By abstracting details away, the program ensures that changes to internal representations do not affect functionalities or dependent code blocks .

The binary search algorithm divides the search interval in half in each step, comparing the target value to the middle element of the array. If the target equals the middle element, it is found; if it's smaller, the search continues on the left half, and if larger, on the right. This process repeats until the target is found or the interval is empty. This algorithm's time complexity is O(log n), making it efficient for large datasets. However, it requires the array to be sorted before searching, which can incur additional computational cost if not already sorted .

Handling division by zero and invalid operations is crucial in calculator applications to ensure correct results and enhance user experience. Division by zero leads to undefined results, which can crash programs if not handled. Invalid inputs, like unsupported operations, can also lead to poor usability. The provided Java code addresses these issues by checking if the divisor is zero before performing division and outputting an error message if so. It also validates the operator input, only performing calculation if a valid operator is provided, otherwise printing 'Error' and prompting user for another operation .

Matrix manipulation in Java often employs multidimensional arrays alongside nested loops for iteration over elements. These structures allow explicit access and modification of matrix elements, essential for tasks like finding minimum values. An outer loop iterates over rows, while an inner loop accesses each column, facilitating comprehensive element-by-element operations. This design supports flexible manipulation, enabling efficient addressing of elements necessary for complex operations and calculations, as demonstrated in determining row-wise and column-wise minima .

You might also like