使用三角形的形式打印乘法表的 Java 程序
在本文中,我们将了解如何以三角形的形式打印乘法表。使用循环可以实现以三角形的形式打印乘法表。
以下是相同的演示 −
输入
假设我们的输入是 −
Input : 7
输出
期望的输出应为 −
The result is : 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49
算法
Step 1 - START Step 2 - Declare 3 integer values namely my_input, I and j Step 3 - Read the required values from the user/ define the values Step 4 – Using two for-loops, iterate from 1 to my_input value and calculate the i*j value. Step 5- Display the result Step 6- Stop
示例 1
此处,用户根据提示输入。您可以在我们的代码实战工具 中对本示例进行现场测试。
import java.util.Scanner; import java.util.*; public class MultiplicationTableTrianglePattern { public static void main(String args[]){ int my_input, i, j; 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.println("Enter a number "); my_input = my_scanner.nextInt(); for (i = 1; i <= my_input; i++) { for (j = 1; j <= i; j++) { System.out.print(i * j + " "); } System.out.println(); } } }
输出
Required packages have been imported A reader object has been defined Enter a number 7 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49
示例 2
此处,整数已预先定义,并且可以在控制台中访问和显示其值。
import java.util.*; public class MultiplicationTableTrianglePattern { public static void main(String args[]){ int my_input, i, j; System.out.println("Required packages have been imported"); my_input = 7; System.out.println("The number is defined as " +my_input ); for (i = 1; i <= my_input; i++) { for (j = 1; j <= i; j++) { System.out.print(i * j + " "); } System.out.println(); } } }
输出
Required packages have been imported The number is defined as 7 1 2 4 3 6 9 4 8 12 16 5 10 15 20 25 6 12 18 24 30 36 7 14 21 28 35 42 49
广告