How To Raise a Number To the Second Power in Java

FacebooktwittertumblrFacebooktwittertumblr

This is one of the articles from our Java Tutorial for Beginners.

Your Task:

To write a method, raising a number to the second power. For example:

Then you have to add the number 2 to the result.

For example:

  • if a user types in the number 2, then the numbers 4 and 6 have to be displayed in the console
  • if a user types in the number 3, then the numbers 9 and 11 have to be displayed in the console
  • if a user types in the number 5, then the numbers 25 and 27 have to be displayed in the console
  • etc.

Solution - 1st approach:

If you run this code on your computer, you will see the following in your console:

25

27

Commentary:

First of all, you have to find out the formula of raising a number to the second power. As you see, the formula will look like this a*a:

That's why we wrote a method called square() with the help of these lines of code:

And in this line of the code we get a number, that will be raised to the second power. Please note, that the number has to be an integer, as we wrote in the code int a:

Then to multiply the number by itself, we wrote this line:

And then we call the method square():

As you can see, in this case we raise the number 5 to the second power. As a result, we get 25 and we assign 25 to the variable called a1.

Then with the help of

the number 25 will be displayed in the console.

And then with the help of

the number 27 wil be displayed in the console.

Solution - the 2nd approach

Commentary:

In this approach, unlike the 1st approach described above, this part of code

has been replaced with

So the formula of raising a number to the second power (a*a) has been written next to "return".

And these lines of code from the 1st approach

have been replaced with

Thefore, we've got fewer lines of code. And still it is an easy-to-read code.


You can find more articles in our Java Tutorial for Beginners.

FacebooktwittertumblrFacebooktwittertumblr

FacebooktwittertumblrFacebooktwittertumblr
Самоучители--узнать детальнее--