Open In App

Printing triangle star pattern using a single loop

Last Updated : 15 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number N, the task is to print the star pattern in single loop.

Examples: 

Input: N = 9
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
Input: N = 5
Output:
*
* *
* * *
* * * *
* * * * *

Please Refer article for printing the pattern in two loops as:
Triangle pattern in Java

Approach 1:

Approach: The idea is to break a column into three parts and solve each part independently of the others.

  • Case 1: Spaces before the first *, which takes care of printing white spaces.
  • Case 2: Starting of the first * and the ending of the last * in the row, which takes care of printing alternating white spaces and *.
  • Case 3: The ending star essentially tells to print a new line or end the program if we have already finished n rows.
    Refer to the image below

Below is the implementation of the above approach:

C++
// C++ implementation of printing
// star pattern in single loop

#include <iostream>
using namespace std;

// Function to print the star
// pattern in single loop
void pattern(int n)
{
    int i, k, flag = 1;

    // Loop to handle number of rows and
    // columns in this case
    for (i = 1, k = 0; i <= 2 * n - 1; i++) {
        // Handles case 1
        if (i < n - k)
            cout << " ";

        // Handles case 2
        else {
            if (flag)
                cout << "*";
            else
                cout << " ";

            flag = 1 - flag;
        }

        // Condition to check case 3
        if (i == n + k) {
            k++;
            cout << endl;

            // Since for nth row we have
            // 2 * n- 1 columns
            if (i == 2 * n - 1)
                break;

            // Reinitializing i as 0,
            // for next row
            i = 0;
            flag = 1;
        }
    }
}

// Driver Code
int main()
{
    int n = 6;

    // Function Call
    pattern(n);
    return 0;
}
Java
// Java implementation of printing
// star pattern in single loop
import java.util.*;

class GFG {

    // Function to print the star
    // pattern in single loop
    static void pattern(int n)
    {
        int i, k, flag = 1;

        // Loop to handle number of rows and
        // columns in this case
        for (i = 1, k = 0; i <= 2 * n - 1; i++) {

            // Handles case 1
            if (i < n - k)
                System.out.print(" ");

            // Handles case 2
            else {
                if (flag == 1)
                    System.out.print("*");
                else
                    System.out.print(" ");

                flag = 1 - flag;
            }

            // Condition to check case 3
            if (i == n + k) {
                k++;
                System.out.println();

                // Since for nth row we have
                // 2 * n- 1 columns
                if (i == 2 * n - 1)
                    break;

                // Reinitializing i as 0,
                // for next row
                i = 0;
                flag = 1;
            }
        }
    }

    // Driver code
    public static void main(String[] args)
    {
        int n = 6;

        // Function Call
        pattern(n);
    }
}

// This code is contributed by offbeat
Python3
# Python3 implementation of
# printing star pattern in
# single loop

# Function to print the star
# pattern in single loop


def pattern(n):

    flag = 1

    # Loop to handle number
    # of rows and columns
    # in this case
    i = 1
    k = 0
    while i <= 2 * n - 1:

        # Handles case 1
        if (i < n - k):
            print(" ", end="")

        # Handles case 2
        else:
            if (flag):
                print("*", end="")
            else:
                print(" ", end="")

            flag = 1 - flag

        # Condition to check case 3
        if (i == n + k):
            k += 1
            print()

            # Since for nth row we
            # have 2 * n- 1 columns
            if (i == 2 * n - 1):
                break

            # Reinitializing i as 0,
            # for next row
            i = 0
            flag = 1

        i += 1


# Driver Code
if __name__ == "__main__":

    n = 6

    # Function Call
    pattern(n)

# This code is contributed by Chitranayal
C#
// C# implementation of printing
// star pattern in single loop
using System;

class GFG {

    // Function to print the star
    // pattern in single loop
    static void pattern(int n)
    {
        int i, k, flag = 1;

        // Loop to handle number of rows and
        // columns in this case
        for (i = 1, k = 0; i <= 2 * n - 1; i++) {

            // Handles case 1
            if (i < n - k)
                Console.Write(" ");

            // Handles case 2
            else {
                if (flag == 1)
                    Console.Write("*");
                else
                    Console.Write(" ");

                flag = 1 - flag;
            }

            // Condition to check case 3
            if (i == n + k) {
                k++;
                Console.WriteLine();

                // Since for nth row we have
                // 2 * n- 1 columns
                if (i == 2 * n - 1)
                    break;

                // Reinitializing i as 0,
                // for next row
                i = 0;
                flag = 1;
            }
        }
    }

    // Driver code
    public static void Main()
    {
        int n = 6;

        // Function call
        pattern(n);
    }
}

// This code is contributed by sanjoy_62
JavaScript
<script>

      // JavaScript implementation of printing
      // star pattern in single loop

      // Function to print the star
      // pattern in single loop
      function pattern(n) {
        var i,
          k,
          flag = 1;

        // Loop to handle number of rows and
        // columns in this case
        for (i = 1, k = 0; i <= 2 * n - 1; i++) 
        {
          // Handles case 1
          if (i < n - k) 
          document.write("&nbsp;&nbsp;");
          // Handles case 2
          else {
            if (flag) 
            document.write("*");
            else 
            document.write("&nbsp;&nbsp;");

            flag = 1 - flag;
          }

          // Condition to check case 3
          if (i == n + k) {
            k++;
            document.write("<br>");

            // Since for nth row we have
            // 2 * n- 1 columns
            if (i == 2 * n - 1) break;

            // Reinitializing i as 0,
            // for next row
            i = 0;
            flag = 1;
          }
        }
      }

      // Driver Code
      var n = 6;
      
      // Function Call
      pattern(n);
      
</script>

Output
     *
    * *
   * * *
  * * * *
 * * * * *
* * * * * *

Time complexity: O(n^2) for given n
Auxiliary space: O(1)

Approach 2:

The idea is to break a column into two parts and solve each part independently of the others in a much simpler manner.

Case 1: Spaces before the first *, which takes care of printing white spaces.

Case 2: Starting of the first * and the ending of the last * in the row, which takes care of printing alternating white spaces and *.

Below is the implementation of the above approach:

C++
#include <iostream>

void pattern(int n)
{
    // Running the 1st loop for the number of rows, so n times.
    for (int i = 0; i < n; i++) {

        // 2nd loop for printing spaces in front of the first star
        for (int j = 0; j < n - i - 1; j++) {
            std::cout << " ";
        }

        // 3rd loop for printing stars and spaces alternatively
        for (int star = 0; star < i + 1; star++) {

            // For not printing a space in front of the 1st star
            // (as it is getting printed by the 2nd loop)
            if (star != 0) {
                std::cout << " ";
            }

            // Printing i+1 stars, i.e., row's number (i) + 1
            std::cout << "*";
        }

        // Printing a new line after the end of each row
        std::cout << std::endl;
    }
}

int main()
{
    int n = 6;

    // Function Call
    pattern(n);

    return 0;
}
// This code is contributed by shivamgupta0987654321
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {

    static void pattern(int n)
    {
        // running 1st loop for number of rows, so n times.
        for (int i = 0; i < n; i++) {

            // 2nd loop for printing spaces in front of
            // first start
            for (int j = 0; j < n - i - 1; j++) {
                System.out.print(" ");
            }

            // 3rd loop for printing stars and spaces
            // alternatively
            for (int star = 0; star < i + 1; star++) {

                // for not printing space in front of 1st
                // star (as it is getting printed by 2nd loop
                if (star != 0) {
                    System.out.print(" ");
                }

                // printing i+1 stars, i.e., row's number(i)
                // + 1
                System.out.print("*");
            }

            // printing new line after the end of each row
            System.out.println("");
        }
    }

    public static void main(String[] args)
    {
        int n = 6;

        // Function Call
        pattern(n);
    }
}
Python3
# Python code of the above approach
def pattern(n):
    # Running the 1st loop for the number of rows, so n times.
    for i in range(n):
        # 2nd loop for printing spaces in front of the first star
        for j in range(n - i - 1):
            print(" ", end=" ")

        # 3rd loop for printing stars and spaces alternatively
        for star in range(i + 1):
            # For not printing a space in front of the 1st star
            # (as it is getting printed by the 2nd loop)
            if star != 0:
                print(" ", end=" ")

            # Printing i+1 stars, i.e., row's number (i) + 1
            print("*", end="")

        # Printing a new line after the end of each row
        print()

if __name__ == "__main__":
    n = 6

    # Function Call
    pattern(n)

# This code is contributed by Susobhan Akhuli
C#
using System;

class Program {
    static void Pattern(int n)
    {
        // Running the 1st loop for the number of rows, so n
        // times.
        for (int i = 0; i < n; i++) {
            // 2nd loop for printing spaces in front of the
            // first star
            for (int j = 0; j < n - i - 1; j++) {
                Console.Write(" ");
            }

            // 3rd loop for printing stars and spaces
            // alternatively
            for (int star = 0; star < i + 1; star++) {
                // For not printing a space in front of the
                // 1st star (as it is getting printed by the
                // 2nd loop)
                if (star != 0) {
                    Console.Write(" ");
                }

                // Printing i+1 stars, i.e., row's number
                // (i) + 1
                Console.Write("*");
            }

            // Printing a new line after the end of each row
            Console.WriteLine();
        }
    }

    static void Main()
    {
        int n = 6;

        // Function Call
        Pattern(n);
    }
}
JavaScript
function pattern(n) {
    // Running the 1st loop for the number of rows, so n times.
    for (let i = 0; i < n; i++) {

        // 2nd loop for printing spaces in front of the first star
        for (let j = 0; j < n - i - 1; j++) {
            process.stdout.write(" ");
        }

        // 3rd loop for printing stars and spaces alternatively
        for (let star = 0; star < i + 1; star++) {

            // For not printing a space in front of the 1st star
            // (as it is getting printed by the 2nd loop)
            if (star !== 0) {
                process.stdout.write(" ");
            }

            // Printing i+1 stars, i.e., row's number (i) + 1
            process.stdout.write("*");
        }

        // Printing a new line after the end of each row
        console.log();
    }
}

const n = 6;

// Function Call
pattern(n);

// This code is contributed by shivamgupta310570

Output
     *
    * *
   * * *
  * * * *
 * * * * *
* * * * * *

Time complexity: O(n^2) for given n

Auxiliary space: O(1)


Printing Triangle Pattern in Python
Visit Course explore course icon
Article Tags :
Practice Tags :

Similar Reads