Java 程序生成乘法表
在本文中,我们将了解如何打印乘法表。使用 for 循环迭代 10 次所需输入以创建乘法表,并在每次迭代中将输入值与 1 到 10 的数字相乘。
下面演示了相同的概念 −
输入
假设我们的输入为 −
Input : 16
输出
理想输出为 −
The multiplication table of 16 is : 16 * 1 = 16 16 * 2 = 32 16 * 3 = 48 16 * 4 = 64 16 * 5 = 80 16 * 6 = 96 16 * 7 = 112 16 * 8 = 128 16 * 9 = 144 16 * 10 = 160
算法
Step 1 – START Step 2 – Declare two integer values namely my_input and i. Step 3 - Read the required values from the user/ define the values Step 4 – Iterate from 1 to 10 using a for-loop, and in each iteration, multiply the numbers 1 to 10 with the input. Step 5- Display the resulting value in after each iteration. Step 6- Stop
示例 1
在这里,用户根据提示输入输入。您可以在代码练习工具中亲身体验此示例 。
import java.util.Scanner; public class MultiplicationTable { public static void main(String[] args) { int my_input, i; my_input = 16; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter a number : "); my_input = my_scanner.nextInt(); System.out.println("The multiplication table of " +my_input + " is :"); for(i = 1; i <= 10; ++i){ System.out.printf("%d * %d = %d \n", my_input, i, my_input * i); } } }
输出
Required packages have been imported A reader object has been defined Enter a number : 16 The multiplication table of 16 is : 16 * 1 = 16 16 * 2 = 32 16 * 3 = 48 16 * 4 = 64 16 * 5 = 80 16 * 6 = 96 16 * 7 = 112 16 * 8 = 128 16 * 9 = 144 16 * 10 = 160
示例 2
在这里,整数已经预先定义,并在控制台上访问和显示其值。
public class MultiplicationTable { public static void main(String[] args) { int my_input, i; my_input = 16; System.out.println("The number is defined as " +my_input); System.out.println("The multiplication table of " +my_input + " is :"); for(i = 1; i <= 10; ++i){ System.out.printf("%d * %d = %d \n", my_input, i, my_input * i); } } }
输出
The number is defined as 16 The multiplication table of 16 is : 16 * 1 = 16 16 * 2 = 32 16 * 3 = 48 16 * 4 = 64 16 * 5 = 80 16 * 6 = 96 16 * 7 = 112 16 * 8 = 128 16 * 9 = 144 16 * 10 = 160
广告