Java Multiplication Table

Hey guys!! Welcome to flower brackets blog. Today we will learn java multiplication table.

Java Multiplication Table

Example: Java Multiplication Table

Now let’s see an example on for loop multiplication table java or multiplication table in java using for loop,

Also Read – Java Program To Find Prime Number

import java.util.Scanner;

public class PrintMultiplicationTables
{
   public static void main(String[] args)
   {
      int a;
      int b;
 
      System.out.println("Please enter an integer to print multiplication tables: ");
      Scanner sc = new Scanner(System.in);
      a = sc.nextInt();
      System.out.println("Multiplication table of " + a + " is : ");
 
      for(b = 1; b <= 10; b++)
         System.out.println(a + " * " + b + " = " + (a * b));
   }
}

Output:

Java Multiplication Table

The above example is not restricted to five multiplication table. You can print multiplication tables of any number in java.


Another Method : Here let’s learn how to print a multiplication table in java from 1 to 20 table

public class MultiplicationTableJava 
{
   public static void main(String[] args) 
   {
      // here we are initializing and setting table size
      final int tableNum = 20;
      // here we are printing row
      System.out.print(" |");
      for(int a = 1; a <= tableNum; a++)
         System.out.print(addSpace(a) + " ");
      System.out.println();
      // here we are printing separator
      System.out.print("---+");
      for(int a = 1; a <= tableNum; a++)
         System.out.print("----");
      System.out.println();
      // now printing main table
      for(int a = 1; a <= tableNum; a++) 
      {
         System.out.print(addSpace(a) + "|");
         for(int b = 1; b <= tableNum; b++) 
         {
            System.out.print(addSpace(a * b) + " ");
         }
         System.out.println();
      }
   }
 
   public static String addSpace(int y) 
   {
      String str = new String();
      if(y < 10) str = " " + y;
      else if(y < 100) str = " " + y;
      else str = "" + y;
      return str;
   }
}

Output:

Java Multiplication Table


conclusion

That’s it guys. This is all about how to create a multiplication table in java or java program for multiplication table using for loop.

I hope you guys have understood multiplication table in java using for loop.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

You May Also Like