Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaJava Program to Print Left Triangle Star Pattern

Java Program to Print Left Triangle Star Pattern

In this article, we will learn about printing Left Triangle Star Pattern.

Examples:

Input : n = 5
Output: 
           * 
         * * 
       * * * 
     * * * * 
   * * * * * 

Left Triangle Star Pattern:

Java




import java.io.*;
 
// java program for left triangle
public class GFG {
    // Function to demonstrate printing pattern
    public static void StarleftTriangle(int k)
    {
        int a, b;
 
        // 1st loop
        for (a = 0; a < k; a++) {
 
            // nested 2nd loop
            for (b = 2 * (k - a); b >= 0; b--) {
                // printing spaces
                System.out.print(" ");
            }
 
            // nested 3rd loop
            for (b = 0; b <= a; b++) {
                // printing stars
                System.out.print("* ");
            }
 
            // end-line
            System.out.println();
        }
    }
 
    // Driver Function
    public static void main(String args[])
    {
        int k = 5;
        StarleftTriangle(k);
    }
}


Output

           * 
         * * 
       * * * 
     * * * * 
   * * * * * 

Time Complexity: O(k2), where k represents the given input.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Using Recursion

Java




import java.io.*;
 
class GFG
{   
      // similar to inner for loop
      public static void printRow(int n, int totalRows)
    {
        if(totalRows == 0)
        {
            return;
        }
           
          if(totalRows <= n) // condition when to print star
        {
            System.out.print(" *");
        }
          else // condition when to print space
        {
            System.out.print("  ");
        }
          printRow(n, totalRows - 1); // moving to next column recursively
    }
       
      // similar to outer for loop
      public static void newRow(int n, int totalRows)
    {
         if(n == 0)
        {
            return;
        }
       
          newRow(n - 1, totalRows);
          printRow(n, totalRows); // prints stars and space in a single row
          System.out.print("\n"); // for new Row.....new line
    }
    public static void main (String[] args)
    {
        GFG.newRow(5, 5); // newRow is static method so no need to create an object of GFG
    }
}


Output

         *
       * *
     * * *
   * * * *
 * * * * *

Time Complexity: O(n)
Auxiliary Space: O(n), Due to recursion stack in memory.

Method: Iterative approach

The idea behind this code is to print a left triangle pattern of stars with a given number of rows.

Step-by-step approach to implement this idea:

  1. Initialize the number of rows to be printed.
  2. Use a loop to iterate through each row, starting from the first row up to the number of rows specified.
  3. For each row, use another loop to print the stars. The number of stars to be printed in each row is equal to the row number. For example, in the first row, only one star is printed, and in the second row, two stars are printed, and so on.
  4. After printing the stars in each row, move to the next line to print the stars in the next row. 

The code above follows this approach by using two nested for loops. The outer loop is responsible for iterating through each row, while the inner loop is responsible for printing the stars in each row. The number of stars printed in each row is determined by the value of the outer loop variable i.

Java




public class LeftTrianglePattern {
    public static void main(String[] args) {
        int numRows = 5;
 
        for (int i = 1; i <= numRows; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}


Output

* 
* * 
* * * 
* * * * 
* * * * * 

Time Complexity:

The outer loop runs numRows times, while the inner loop runs i times in each iteration of the outer loop. Therefore, the total number of iterations is 1 + 2 + 3 + … + numRows, which is equal to numRows(numRows+1)/2. Therefore, the time complexity of the code is O(numRows^2).

Auxiliary Space:

The code uses a constant amount of auxiliary space to store the values of numRows, i and j. Therefore, the auxiliary space complexity of the code is O(1).

Approach Name: Using nested for loops

Steps:

  1. Take input n from the user.
  2. Use two nested for loops to print the left triangle star pattern.
  3. The outer loop runs from 1 to n and the inner loop runs from 1 to i.
  4. In each iteration of the inner loop, a star is printed.
  5. After each row is printed, a new line is printed.

Java




public class LeftTriangleStarPattern {
    public static void printLeftTriangle(int n) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        int n = 5;
        printLeftTriangle(n);
    }
}


Output

* 
* * 
* * * 
* * * * 
* * * * * 

Time Complexity: O(n^2)

Auxiliary Space: O(1) 

Approach: Java 8 Stream-based Left Triangle Star Pattern Printer 

  1. Initialize an integer n to the desired number of rows for the left triangle star pattern.
  2. Use Java’s IntStream to iterate over each row number from 1 to n.
  3. For each row, use another IntStream to iterate over each column number from 1 to the current row number.
  4. Map each column number to a string consisting of a single star followed by a space character.
  5. Collect the mapped strings into a single string using Collectors.joining().
  6. Use System.out.printf() to print the resulting string with left alignment and a width of n*2 to account for the spacing between stars.
  7. Repeat steps 3 to 6 for each row number.
  8. The resulting output will be the left triangle star pattern for n rows.

Java




import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
public class LeftTriangleStarPattern {
    public static void main(String[] args)
    {
        int n = 5;
 
        IntStream.range(1, n + 1).forEach(row -> {
            String stars
                = IntStream.range(1, row + 1)
                      .mapToObj(i -> "* ")
                      .collect(Collectors.joining());
            System.out.printf("%" + n * 2 + "s%n", stars);
        });
    }
}


Output

        * 
      * * 
    * * * 
  * * * * 
* * * * * 

Time complexity: O(n2)
Auxiliary space: O(n)

RELATED ARTICLES

Most Popular

Recent Comments