Given the an array of integers, you will build an function that will multiply ea
ID: 3876403 • Letter: G
Question
Given the an array of integers, you will build an function that will multiply each one times 2 and then return the array back to the main method and output it.
1. In your main method, declare and define an array of at least 5 integer elements.
a. For this one problem, the array should be hard-coded and not from user prompted values.
2. Create a function that receives this array of ints.
3. Create a loop to cycle through the array and multiply each element by 2.
a. Remember this loop must work for an array of any size!
b. You must NOT hard coding it!
4. Return this “doubled” array to the main method.
5. Output both the original and “doubled” array in the main method. NOT in the custom function.
a. You may use a loop to output the arrays or you may convert them to a string and output that.
Explanation / Answer
public class DoubleArray {
public DoubleArray() {
}
// function which multiply 2 to each element of array and then return the doubled array.
public static int[] multiply2Array(int[] array){
int[] doubleArray = new int[array.length];
int i = 0;
//for loop in array
for (int element:array){
doubleArray[i] = element*2;
i++;
}
return doubleArray;
}
//convert array to string and print it
public static void printArray(int[] array){
System.out.print("[");
//for loop in from 0 to array length
for (int i=0;i<array.length;i++){
if (i == array.length-1){
System.out.print(array[i]);
}
else{
System.out.print(array[i] + ",");
}
}
System.out.println("]");
}
public static void main(String[] args) {
//create array of five elements you can increase number of elements.
int[] array = {1,7,19,22,39};
int[] doubleArray = DoubleArray.multiply2Array(array);
System.out.println("The array is: ");
//print array
DoubleArray.printArray(array);
System.out.println("The array after doubled is: ");
//print doubled array
DoubleArray.printArray(doubleArray);
}
}
Sample Output:
The array is:
[1,7,19,22,39]
The array after doubled is:
[2,14,38,44,78]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.