Write a Java Program to Print Multiplication Table using For Loop, and While Loop with example
Java Program to Print Multiplication Table using For Loop
This Java program for Multiplication table allows the user to enter any integer value, and prints the multiplication table from that number to 9 using For Loop.
// Java Program to Print Multiplication Table import java.util.Scanner; public class MultiplicationTable { private static Scanner sc; public static void main(String[] args) { int number, i, j; sc = new Scanner(System.in); System.out.print(" Please Enter any Number : "); number = sc.nextInt(); for(i = number; i < 10; i++) { for(j = 1; j <= 10; j++) { System.out.println(i +" * " + j + " = " + i * j); } System.out.println("================"); } } }
OUTPUT
ANALYSIS
Within this Java multiplication table example, the first For loop is to iterate from user entered value to 9. Next, we used Nested For Loop to iterate j from 1 to 10
User entered value: number = 9
First For Loop – First Iteration: for(i = 9; i < 10; i++)
Condition is True. So, it enters into the second For Loop
Second For Loop – First Iteration: for(j = 1; 1 <= 10; 1++)
Condition is True. So, the statement inside the Java system.out.println printed.
Second For Loop – Second Iteration: for(j = 2; 2 <= 10; 2++)
Condition is True. So, the statement inside it printed.
The second For Loop repeats the process until j reaches 11. Because if j is 11, the condition fails so, it exits from the second loop.
First For Loop – Second Iteration: for(i = 10; i < 10; i++)
Condition (10 < 10) Fails. So, it exits from the First For Loop
Java Program to display Multiplication Table using While Loop
This Java Multiplication table example is the same as above, but we are using the While Loop.
// Java Program to Print Multiplication Table import java.util.Scanner; public class MultiplicationTable1 { private static Scanner sc; public static void main(String[] args) { int i, j; sc = new Scanner(System.in); System.out.print(" Please Enter any Number : "); i = sc.nextInt(); while(i < 10) { j = 1; while(j <= 10) { System.out.println(i +" * " + j + " = " + i * j); j++; } System.out.println("================"); i++; } } }
OUTPUT
Java Program for Multiplication Table using Method
This Java program is the same as the first example. But we separated the Java multiplication logic and placed it in a separate method.
// Java Program to Print Multiplication Table import java.util.Scanner; public class MultiplicationTable2 { private static Scanner sc; public static void main(String[] args) { int number; sc = new Scanner(System.in); System.out.print(" Please Enter any Number : "); number = sc.nextInt(); MultiTable(number); } public static void MultiTable(int num) { int i, j; for(i = num; i < 10; i++) { for(j = 1; j <= 10; j++) { System.out.println(i +" * " + j + " = " + i * j); } System.out.println("================"); } } }
OUTPUT