Multiplication table generation in java

              Multiplication is one of the basic operations in mathematics. Basically, it deals with numbers.

When two numbers are multiplied, it actually a repetitive addition.

Eg:

2X3

2+2+2 =6. Here, 2 is added in three times continuously.

Let us implement multiplication table in java.

Logic:

  • Get the number and number of elements from the user to generate the multiplication table.
  • Using a for loop, repeat the process, multiply the number with 1 to number of elements.
  • Print the output as multiplication table.

Program implementation:

  • First, include the built in package java.util.Scanner.
  • Create a public class with main() function.
  • Create an object for Scanner class.
  • Using the object, call the nextInt() function to read the inputs.
  • With the use of 'for' loop, print the output.

Program:

import java.util.Scanner;

public class GenerateMTable{

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        // Get the user input for multiplication table

        System.out.print("Enter the number to generate multiplication table: ");

        int no = s1.nextInt();

        // Enter the number of elements in the table.

        System.out.print("Enter the number of the elements: ");

        int n = s1.nextInt();

        // print the multiplication table

        System.out.println( "Multiplication table For:" +no);

        for (int i = 1; i <= n; i++) {

            System.out.println(no + " x " + i + " = " + (no * i));

        }

        s1.close();

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac GenerateMTable.java

C:\raji\blog>java GenerateMTable

Enter the number to generate multiplication table: 5

Enter the number of the elements: 10

Multiplication table For:5

5 x 1 = 5

5 x 2 = 10

5 x 3 = 15

5 x 4 = 20

5 x 5 = 25

5 x 6 = 30

5 x 7 = 35

5 x 8 = 40

5 x 9 = 45

5 x 10 = 50

That’s all. The java program to implement the multiplication table is done. Keep coding.

No comments:

Post a Comment