← Home

Powers

1public class Ex9 {
2  public static void main(String[] args) {
3    int alpha = 5;
4    double beta = Math.pow(5, 2);
5    System.out.println("5 to the power of 2 is " + beta);
6
7    int gamma = 5.5;
8    double delta = Math.pow(5.5, 2.2);
9    System.out.println("5.5 to the power of 2 is " + delta);
10
11    int epsilon = 10;
12    int zeta = (int) Math.pow(5, 2);
13    System.out.println("5 to the power of 2.2 is " + zeta);
14
15    int eta = 4;
16    double sqrt = Math.sqrt(4);
17    System.out.println("The square root of 4 is " + sqrt);
18
19    int theta = 5;
20    sqrt = Math.sqrt(5);
21    System.out.println("The square root of 5 is " + sqrt);
22  }
23}

Explanation

  1. In this exercise, we introduce the functions Math.pow() and Math.sqrt(). Math.pow() puts the first argument to the power of the second argument. It takes a double for both its arguments, hence why we can do Math.pow(5.5, 2.2). It's fine to put integers as its arguments, since integers can be implicitly cast to doubles. Math.sqrt() takes one double as an argument, and returns its square root. Math.pow() and Math.sqrt() return doubles as well.

  2. If you want to store the values returned from Math.pow() and Math.sqrt() as integers, as in line 13, then you must explicitly cast it by putting (int) in front of the double you want to cast to an int. The reason that doubles aren't implicitly cast to integers is because doubles are more precise.

Extension Programs

  1. Use a for loop, to write a program that prints out all the numbers between 1 to 100, squared.

  2. Use a for loop, to write a program that prints out 2 to the power of 1, 2 to the power of 2, all the way to 2 to the power of 16.

  3. Given that momentum = mass * (velocity to the power of 2), write a program to calculate momentum given mass and velocity. You will need to store mass and velocity as variables, and calculate momentum from the variables.

  4. Write a program to calculate BMI (Body Mass Index) using the formula: BMI = mass / (height to the power of 2). You will need to store mass and height as variables, and calculate BMI from the variables.