Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để in Mẫu hình sao tam giác trái

Trong bài này, chúng ta sẽ hiểu về cách in hình ngôi sao tam giác trái. Mẫu được hình thành bằng cách sử dụng nhiều vòng lặp for và câu lệnh in.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

Enter the number of rows : 8

Đầu ra

Đầu ra mong muốn sẽ là -

The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *

Thuật toán

Step 1 - START
Step 2 - Declare three integer values namely i, j and my_input
Step 3 - Read the required values from the user/ define the values
Step 4 - We iterate through two nested 'for' loops to get space between the characters.
Step 5 - After iterating through the innermost loop, we iterate through another 'for' loop. This will help print the required character.
Step 6 - Now, print a newline to get the specific number of characters in the subsequent lines.
Step 7 - Display the result
Step 8 - Stop

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử ví dụ này trực tiếp trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java để in Mẫu hình sao tam giác trái .

import java.util.Scanner;
public class RightTriangle{
   public static void main(String args[]){
      int i, j, my_input;
      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 the number of rows : ");
      my_input = my_scanner.nextInt();
      System.out.println("The right triangle star pattern : ");
     for (i=0; i<my_input; i++){
        for (j=2*(my_input-i); j>=0; j--){
           System.out.print(" ");
        }
        for (j=0; j<=i; j++ ){
           System.out.print("* ");
        }
        System.out.println();
     }
   }
}

Đầu ra

Required packages have been imported
A reader object has been defined
Enter the number of rows : 8
The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *

Ví dụ 2

Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.

public class RightTriangle{
   public static void main(String args[]){
      int i, j, my_input;
      my_input = 8;
      System.out.println("The number of rows is defined as " +my_input);
      System.out.println("The right triangle star pattern : ");
      for (i=0; i<my_input; i++){
         for (j=2*(my_input-i); j>=0; j--){
            System.out.print(" ");
         }
         for (j=0; j<=i; j++ ){
            System.out.print("* ");
         }
         System.out.println();
      }
   }
}

Đầu ra

The number of rows is defined as 8
The right triangle star pattern :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *