In: Computer Science
public class AddValueNewArray { // You must define the addValueNew method, which behaves // similarly to the addValueTo method in AddValueToArray.java. // However, instead of adding the given value to the given // array, it will return a _new_ array, where the new array // is the result of adding the value to each element of the // given array. To be clear, the given array NEVER CHANGES. // // TODO - define your code below this comment // // DO NOT MODIFY printArray! public static void printArray(int[] array) { for (int index = 0; index < array.length; index++) { System.out.println(array[index]); } } public static void main(String[] args) { int[] array = new int[]{3, 8, 6, 4}; int valueToAdd = Integer.parseInt(args[0]); int[] newArray = addValueNew(valueToAdd, array); System.out.println("Original array:"); printArray(array); System.out.println("New array:"); printArray(newArray); } }
Since this program takes input from CLI it would be better if you run this code in command prompt
File name is AddValueNewArray.java
I have explained what the code does in comments in the code
public class AddValueNewArray {
// You must define the addValueNew method, which behaves
// similarly to the addValueTo method in AddValueToArray.java.
// However, instead of adding the given value to the given
// array, it will return a _new_ array, where the new array
// is the result of adding the value to each element of the
// given array. To be clear, the given array NEVER CHANGES.
//
// TODO - define your code below this comment
//
public static int[] addValueNew(int value, int[] old_array){
// length of old array
int l = old_array.length;
// creating new array of size l
int[] new_array = new int[l];
// for loop for adding each element
// old array with value and storing it in new_array
for (int i=0; i<l; i++){
new_array[i] = old_array[i]+value;
}
//returning the new array
return new_array;
}
// DO NOT MODIFY printArray!
public static void printArray(int[] array) {
for (int index = 0; index < array.length; index++) {
System.out.println(array[index]);
}
}
public static void main(String[] args) {
int[] array = new int[]{3, 8, 6, 4};
int valueToAdd = Integer.parseInt(args[0]);
int[] newArray = addValueNew(valueToAdd, array);
System.out.println("Original array:");
printArray(array);
System.out.println("New array:");
printArray(newArray);
}
}
Hope this answers your questions, please leave a upvote if you find this helpful.