Below is the java code for printing the multiplication table.
import java.util.Scanner;
class Multiplication_table
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int number = sc.nextInt();
for(int i = 1;i<=10;i++)
{
System.out.println(number+" X "+i+" = "+number*i);
}
}
}
Demonstration:
1. First, Scanner class is imported.
2. A class namely Multiplication_table have been defined.
3. A main method have been defined.
4. Object of Scanner class have been created.
5. A Number has been demanded from user by giving a message.
6. To accept and store the number, a variable namely number has been defined of int data type.
7. Used for loop and initialized an int variable namely i by 1 and given the condition as i<=10 that means, loop will keep on executing from 1 to 10.
8. Within for loop block, System.out.println(number+" X "+i+" = "+number*i); is mentioned which means:
a) First value in number variable will be displayed. This is the number given by user.
b) Then, X will be displayed. During final output, you will understand its purpose.
c) Then, present value of i will be displayed. Due to loop, it will keep on executing from 1 to 10.
d) Finally, product of number and i will get displayed.
7. Used for loop and initialized an int variable namely i by 1 and given the condition as i<=10 that means, loop will keep on executing from 1 to 10.
8. Within for loop block, System.out.println(number+" X "+i+" = "+number*i); is mentioned which means:
a) First value in number variable will be displayed. This is the number given by user.
b) Then, X will be displayed. During final output, you will understand its purpose.
c) Then, present value of i will be displayed. Due to loop, it will keep on executing from 1 to 10.
d) Finally, product of number and i will get displayed.
Output of the code will be as displayed in the below diagram. As it can be seen that as per demanded by the program to enter a number, we have given 15 which means that multiplication table of 15 needs to be displayed.
Immediately, after pressing enter, the following output will come:
Now, type the program in BlueJ or any other Online Java compiler and run the code and test it with different numbers.
Happy Coding ........
No comments:
Post a Comment