Java Question Write a static method that allocates memory fo
Java Question:
Write a static method that allocates memory for numElems floats (where numElems is an int parameter) AND initializes each element to a float value (another parameter) to the power of its index (i.e., the index is the exponent), then return the array in a return statement (see the one-dim. array example). Write another static method that displays the array backwards, BUT DON\'T CHANGE THE ARRAY (the ONLY parameter MUST be the array, nothing else)! In main, declare an array of floats variable, call the first method passing 9 and 5.0 (assign to the main array variable), then call the 2nd method passing the array variable.
Solution
ArrayDemo.java
import java.util.Scanner;
public class ArrayDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(\"Enter array size: \");
int n = scan.nextInt();
System.out.println(\"Enter a number: \");
float f = scan.nextFloat();
float a[] = getArray(n, f);
displayArray(a);
}
public static float[] getArray(int n, float f){
float a[] = new float[n];
for(int i=0; i<a.length; i++){
a[i] = (float) Math.pow(f, i);
}
return a;
}
public static void displayArray(float a[]){
for(int i=a.length-1; i>=0; i--){
System.out.print(a[i]+\" \");
}
System.out.println();
}
}
Output:
Enter array size:
9
Enter a number:
5.0
390625.0 78125.0 15625.0 3125.0 625.0 125.0 25.0 5.0 1.0
