Question 1: [10]
You are given a .java code file named “Q1.java”. Your task is to read the comments in that
Also, you will need to write code in the main method and test all your methods.
Method Details
The details of the methods are as follows:
1. printIntArray Method
This method prints the values of the argument int array.
2. insertKey Method
This method inserts the given key value at index 0 in the array. If the array already has a value at index 0,
it will shift the values to the right and make space for the new key.
3. removeKey Method
This method performs the opposite function of the above method and removes and returns the key
To remove the first key, we will first store that value and then shift all values one place to the left as given
4. copyArray Method
This method copies all values from the argument array to a new array. It then returns the newly copied
array.
5. arraysEqual Method
This method returns true if both the argument arrays have the exact same values. Otherwise, returns false.
import java.util.*;
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.print("Enter key: ");
int key = keyBoard.nextInt();
int arr[] = new int[0];
arr = insertKey(arr, key);
printIntArray(arr);
System.out.println(removeKey(arr));
printIntArray(arr);
int copyArr[] = copyArray(arr);
printIntArray(copyArr);
int arr1[] = { 4, 5, 4, 6, 45 };
int arr2[] = { 4, 5, 4, 6, 45 };
System.out.println(arraysEqual(arr1, arr2));
keyBoard.close();
}
static void printIntArray(int arr[]) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
static int[] insertKey(int arr[], int key) {
int i;
int n = arr.length;
int newarr[] = new int[n + 1];
for (i = 0; i < n; i++) {
newarr[i + 1] = arr[i];
}
newarr[0] = key;
return newarr;
}
static int removeKey(int arr[]) {
int i;
int n = arr.length;
int key = arr[0];
int newarr[] = new int[n - 1];
for (i = 0; i < n - 1; i++) {
newarr[i] = arr[i + 1];
}
arr = new int[newarr.length];
for (i = 0; i < newarr.length; i++) {
arr[i] = newarr[i];
}
return key;
}
static int[] copyArray(int arr[]) {
int n = arr.length;
int copyArr[] = new int[n];
for (int i = 0; i < n; i++) {
copyArr[i] = arr[i];
}
return copyArr;
}
static boolean arraysEqual(int arr1[], int arr2[]) {
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr2.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
}
Comments
Leave a comment