Introduction to Java Programming Comprehensive Version 10th
Introduction to Java Programming, Comprehensive Version (10th Edition)
Methods And Arrays
Compute the powers of 2 and store them in the integer array power with 10 elements. That is store 1,2,4,8,16,32... etc. Use a for loop and the Math.pow to raise the 2 to the power of the index. Be sure to cast the Math.pow results to an int. Also, print out each of the elements in the array.
Solution
Code to copy:
public class PowerTest2 {
public static void main(String[] args) {
int result = Math.pow(20, 5);
System.out.println(\"The power of these numbers is: \" + result);
{
for (int k = 1; k <= 10; k++) {
for (int j = 1; j <= 3; j++) {
int loopResult = Math.pow(k, j);
System.out.println(k + \" to the power of \" + j + \" is: \"
+ loopResult);
}
}
}
{
int[][] array3d = new int [10] [3];
{
for (int k = 0; k < array2d.length; k++) {
for (int j = 0; j < array2d[0].length; j++) {
{
int loopResult = Math.pow(k, j);
array2d[k][j] = loopResult;
System.out.println(\"The variable at \" + ik+ \" \" + j
+ \" is: \" + array2d[k][j]);
}
}
}
}
public static int Math.pow(int a, int b) {
int s = a;
int result = a;
for (int i = 1; i < b; i++) {
s = s * a;
result = s;
}
return result;
}
}

