Friday, September 22, 2017

// // Leave a Comment

Java Program to Print Table Using Loop

Java program to print a table

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.

0 comments:

Post a Comment


DISCLAIMER: Opinions expressed in comments are those of the comment writers alone and does not reflect or represent the views of the post author. We reserve the right to delete any post deemed inappropriate or offensive and/or spammy. Please do not use abusive words/hate speech.

I Appreciate your valuable Feedback. So, Please DO NOT SPAM - Spam comments will be deleted immediately.

Don't use brand name in name field and you're not allowed to use links in comments unless it's necessary. Such comments will be removed immediately. To get notified of replies or follow-up comments, click the box next to notify me.

Thanks.