Below is a simple Java program to print a table using loops and Math.pow() function. Alternative solution to Introduction to Java Programming Chapter 2 Exercise 2.14. I decided to write this because a user made a comment about using for loops to solve the problem but his code didn't produce the required results.
public class PrintTable { public static void main(String [] args) { System.out.println("a"+ "\t" + "a^2" + "\t" + "a^3"); for (int j = 0; j < 4; j++) { System.out.println((j+1) + "\t" + ((j+1)*(j+1)) + "\t" + ((j+1)*(j+1)*(j+1))); } } }
Or you can use the Math.pow() function to achieve the same result.
import java.lang.Math; public class PrintTable { public static void main(String [] args) { System.out.println("a"+ "\t" + "a^2" + "\t" + "a^3"); for (int j = 0; j < 4; j++) { System.out.println((j+1) + "\t" + (int)Math.pow((j+1),2) + "\t" + (int)Math.pow((j+1),3)); } } }
Click here to see other solutions to Introduction to Java Programming.