How To Raise a Number To a Power in Java
This is one of the articles from our Java Tutorial for Beginners.
Your Task:
You have to write a method, raising a number to the third power. For example:
Solution:
1 2 3 4 5 6 7 8 9 |
public class Test{ static int cube(int a){ return a*a*a; } public static void main(String[] args){ System.out.println( cube(2) ); } } |
If you run this code on your computer, you will see the following in your console:
8
Commentary:
First of all, you have to find out the formula of raising a number to the third power. As you see, the formula will look like this a*a*a:
That's why we wrote a method with the help of these lines of code:
1 2 3 |
static int cube(int a){ return a*a*a; } |
And then we called the method for the number 2:
1 2 3 |
public static void main(String[] args){ System.out.println( cube(2) ); } |
As a result, we've got the number 8 in the console.
You can find more articles in our Java Tutorial for Beginners.