In this Article, we will write a program to generate multiplication table of the given number in Java. This will be done using for loops and while loops.
Program to Generate Multiplication Table Using For Loop:
import java.util.*;
public class Main{
public static void main(String[] args) {
// Scanner class for taking input
Scanner scn = new Scanner(System.in);
int num = scn.nextInt();
// Loop to print the table
for(int i = 1; i <= 10; i++){
// Printing the table
System.out.println(num + " * " + i + " = " + num * i);
}
}
}
The program starts by creating an instance of the Scanner class to take user input.
It prompts the user to enter an integer, which is then stored in the variable num.
A for loop is used to iterate from i = 1 to i = 10, representing the numbers in the multiplication table.
Inside the loop, the multiplication table is printed using the System.out.println statement.
The statement concatenates the values of num, i, and num * i to form the output string. a. num represents the input number provided by the user. b. i represents the current iteration value, ranging from 1 to 10. c. num * i calculates the result of multiplying num with i.
The output displays the equation num * i = num * i for each iteration of the loop, showing the multiplication table.
After the loop finishes executing, the program ends.
The output is the multiplication table for the given input number, ranging from 1 to 10.
Explanation:In the above Example, We are taking an input of a number for which the multiplication table have to be print. For loop is used for printing the multiplication table.
Program to Create Multiplication Table Using While Loop:
import java.util.*;
public class Main{
public static void main(String[] args) {
// Scanner class for taking input
Scanner scn = new Scanner(System.in);
int num = scn.nextInt();
int i = 1;
// Loop to print the table
while(i <= 10){
// Printing the table
System.out.println(num + " * " + i + " = " + num * i);
i++;
}
}
}
Explanation:In the above Example, We are taking an input of a number for which the multiplication table have to be print. While loop is used for printing the multiplication table.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment