Java 程序:打印倒镜像直角三角形
原文:https://www.studytonight.com/java-programs/java-program-to-print-inverted-mirrored-right-triangle
在本教程中,我们将看到如何在 java 中打印倒置的镜像直角三角形。首先,我们将要求用户初始化行数。然后,我们将使用不同的循环来打印反向镜像的直角三角形图案。但是在继续之前,如果你不熟悉 java 中循环的概念,那么一定要查看关于 Java 中循环的文章。
输入:输入行数:6
输出:
**
*
这可以通过使用以下方法来实现:
方法 1:使用 For 循环
方法 2:使用 While 循环
方法 3:使用边做边循环
让我们看看这些方法中的每一种,以便更好地理解。
Java 程序:程序 1:打印倒镜像直角三角形
在这个程序中,我们将看到如何使用 for 循环在 java 中打印倒置的镜像直角三角形。
算法:
开始
创建 Scanner 类的实例。
声明变量来存储行数和模式符号。
要求用户初始化这些变量。
使用三个循环来打印图案。
外部 for 循环将遍历行。
第一个内部 for 循环用于打印所需的空间。
第二个内部 for 循环打印所需的模式符号。
显示结果。
停下来。
让我们看下面的例子来理解上面算法的实现。
//Java Program to print the Inverted Mirrored Right Triangle
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int n=sc.nextInt();
System.out.println("Enter the symbol: ");
char ch = sc.next().charAt(0);
for(int i=n;i>0;i--)
{
for(int j=n-i;j>0;j--)
{
System.out.print(" ");
}
for(int j=0;j<i;j++)
{
System.out.print(ch);
}
System.out.println();
}
}
}
输入行数:7 输入符号:*
- T4】
- *
- *
- *
Java 程序:程序 2:打印倒镜像直角三角形
在这个程序中,我们将看到如何使用 while 循环在 java 中打印反向镜像直角三角形。
算法:
开始
创建 Scanner 类的实例。
声明变量来存储行数和模式符号。
要求用户初始化这些变量。
使用三个 while 循环来打印图案。
外部 while 循环将遍历行。
第一个内部 while 循环用于打印所需的空间。
第二个内部 while 循环打印所需的模式符号。
显示结果。
停下来。
让我们看下面的例子来理解上面算法的实现。
//Java Program to print the Inverted Mirrored Right Triangle
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int n=sc.nextInt();
System.out.println("Enter the symbol: ");
char ch = sc.next().charAt(0);
int i=n,j;
while(i>0)
{
j=n-i;
while(j-->0)
{
System.out.print(" ");
}
j=0;
while(j++<i)
{
System.out.print(ch);
}
System.out.println();
i--;
}
}
}
输入行数:6 输入符号:*
Java 程序:程序 3:打印倒镜像直角三角形
在这个程序中,我们将看到如何使用 do-while 循环在 java 中打印倒置的镜像直角三角形。
算法:
开始
创建 Scanner 类的实例。
声明变量来存储行数和模式符号。
要求用户初始化这些变量。
使用三个边做边循环来打印图案。
外部 do-while 循环将遍历行。
第一个内部 while 循环用于打印所需的空间。
第二个内部边做边循环打印所需的图案符号。
显示结果。
停下来。
让我们看下面的例子来理解上面算法的实现。
//Java Program to print the Inverted Mirrored Right Triangle
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int n=sc.nextInt();
System.out.println("Enter the symbol: ");
char ch = sc.next().charAt(0);
int i=n,j;
do
{
j=n-i;
while(j-->0)
{
System.out.print(" ");
}
j=0;
do
{
System.out.print(ch);
}while(++j<i);
System.out.println();
}while(--i>0);
}
}
输入行数:8 输入符号:*
- *