Arrays: Practice Problems III
Time for taking it to the next level!
Problem1: Write a java program to insert an element in an array.
Note: Position provided in the input is 1-indexed.
Input
Number of elements: 5
Elements: 10 20 30 40 50
Element to be added: 25
Position where to insert: 3
Output
10, 20, 25, 30, 40, 50
Approach
Explanation/Steps
Suppose you have a list of things you need to buy at the grocery store, and you have noted these items on a piece of paper. The list is:
- Apple
- Banana
- Bread
- Milk
This list is like an array where each item is an element, and the order represents the index.
Let's say we want to insert Eggs at the 3rd position now.
To achieve this, we will follow these steps:
- Create a new array with a size one greater than the previous one.
- Copy all the elements from the previous to this new array up to the position provided in the input.
- Next, insert the element to be inserted (in this case, Eggs).
- Finally, copy the rest of the elements from the previous array to the new array, one by one.
After following these steps, we can successfully insert an element into the array at a particular position.
Solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Input size of the array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of the array: ");
int size = scanner.nextInt();
int [] arr = new int[size];
// Input elements in array
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
// Input new element and position to insert
System.out.println("Enter element to insert: ");
int num = scanner.nextInt();
System.out.println("Enter the element position: ");
int pos = scanner.nextInt();
// If position of element is not valid
if (pos > size + 1 || pos <= 0) {
System.out.printf("Invalid position! Please enter position between 1 to %d\n", size + 1);
} else {
//Creating new array with size + 1
int[] newArr = new int[size + 1];
//Copy elements till position
for(int i = 0; i < pos - 1; i++){
newArr[i] = arr[i];
}
//Inserting the new element
newArr[pos - 1] = num;
//Copying the rest elements
for(int i = pos; i <= size; i++){
newArr[i] = arr[i - 1];
}
// Print array after insert operation
System.out.print("Array elements after insertion: ");
for (int i = 0; i <= size; i++) {
System.out.print(newArr[i] + " ");
}
}
scanner.close();
}
}
Program2: Write a java program to delete element from array at specified position.
Note: Position provided in the input is 1-indexed.
Input
No of elements: 5
Elements: 10 20 30 40 50
Position to delete: 2
Output
10 30 40 50
Approach
Hint
Use the grocery list we made in the previous problem. Let's say we don't want to buy breads now. Don't just strike the item XD!
Think of the list in terms of array. We can also create a new list but attempt to do so without creating a new array.
Explanation/Steps
All we have to do is move the things from the specified position one place to the left of where they are now.
- Use the element at index "position" to begin the iteration.
- Add the value of the current item to the preceding element's.
Solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Input size and elements in array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of the array: ");
int size = scanner.nextInt();
//Creating the array
int[] arr = new int[size];
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
// Input element position to delete
System.out.println("Enter the element position to delete: ");
int pos = scanner.nextInt();
// Check for invalid delete position
if (pos <= 0 || pos > size) {
System.out.printf("Invalid position! Please enter position between 1 to %d", size);
} else {
// Copy next element value to current element
for (int i = pos - 1; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
// Decrement array size by 1
size--;
// Print array after deletion
System.out.print("\nElements of array after delete are: ");
for (int i = 0; i < size; i++) {
System.out.printf("%d\t", arr[i]);
}
}
scanner.close();
}
}
Problem 3: Write a java program to copy all elements from an array to another array.
Input
10
10 1 95 30 45 12 60 89 40 -4
Output
Array1: 10 1 95 30 45 12 60 89 40 -4
Array2: 10 1 95 30 45 12 60 89 40 -4
Approach
Hint
Hints? Who needs them? No hints required; you've got this!"
Explanation
- Firstly, input the original array as usual.
- Now, since we need to copy the elements to another array, declare another array of same size.
- Iterate through the original array and copy elements one by one to the final array.
- That's it! Print the arrays to check the contents of the array.
Solution
import java.util.Scanner;
public class CopyArray {
public static void main(String[] args) {
// Input size of the array
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
//Declare the array
int[] source = new int[size];
int[] dest = new int[size];
// Input array elements
for (int i = 0; i < size; i++) {
source[i] = scanner.nextInt();
}
// Copy all elements from source array to dest array
for (int i = 0; i < size; i++) {
dest[i] = source[i];
}
// Print all elements of source array
System.out.print("Array1: ");
for (int i = 0; i < size; i++) {
System.out.print(source[i] + "\t");
}
System.out.println();
// Print all elements of dest array
System.out.print("Array2: ");
for (int i = 0; i < size; i++) {
System.out.print(dest[i] + "\t");
}
scanner.close();
}
}
Problem 4: Write a java program to input elements in array and print all unique elements of that array.
Input
1, 2, 3, 5, 1, 5, 20, 2, 12, 10
Output
3, 20, 12, 10
Approach
Hint
Could you please once check if all the items in our grocery list are unique?
How did you do that? You must have started with the first item, checked it with every other item. If it does not match with any other item, it is unique. Right?
We need to apply the same concept here.
Explanation/Steps
- Iterate through each element in the array using a loop.
- For each element at position
i
, set a boolean variableisUnique
totrue
, considering that the element is unique initially. - Use another loop to compare the element at position
i
with all other elements in the array at different positions (j
). - If a matching element is found at a different position, set
isUnique
tofalse
and break out of the loop. That means the element is not unique. - If
isUnique
is stilltrue
after the inner loop, print the element at positioni
as it is unique.
Solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Input size of array and elements in array
Scanner scanner = new Scanner(System.in);
System.out.println("Enter size of array: ");
int size = scanner.nextInt();
// Creating array
int[] arr = new int[size];
System.out.println("Enter elements in array: ");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
// Print all unique elements of array
System.out.println("Unique elements in the array are: ");
for (int i = 0; i < size; i++) {
boolean isUnique = true;
// Checking with all elements of the array
for (int j = 0; j < size; j++) {
// Since both the elements at different position have equal value,
// that means the current element is not unique
if (i != j && arr[i] == arr[j]) {
isUnique = false;
break;
}
}
if (isUnique) {
System.out.print(arr[i] + " ");
}
}
System.out.println();
scanner.close();
}
}
Similarly you can even print the duplicate elements.
Bravo! See you in the next article!