Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

왼쪽 삼각형 별 패턴을 인쇄하는 Java 프로그램

<시간/>

이 기사에서는 왼쪽 삼각형 별 패턴을 인쇄하는 방법을 이해합니다. 패턴은 여러 for 루프와 인쇄 문을 사용하여 형성됩니다.

아래는 동일한 데모입니다 -

입력

입력이 -

라고 가정합니다.
Enter the number of rows : 8

출력

원하는 출력은 -

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

알고리즘

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

예시 1

여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다. 왼쪽 삼각형 별 패턴을 인쇄하는 Java 프로그램 .

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();
     }
   }
}

출력

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

예시 2

여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.

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();
      }
   }
}

출력

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