Impresión de patrón de estrella triangular usando un solo bucle

Dado un número N , la tarea es imprimir el patrón de estrella en un solo ciclo .

Ejemplos: 

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

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

Consulte el artículo para imprimir el patrón en dos bucles como:
patrón de triángulo en Java

Planteamiento: La idea es dividir una columna en tres partes y resolver cada parte independientemente de las demás.

  • Caso 1: Espacios antes del primer *, que se encarga de imprimir los espacios en blanco.
  • Caso 2: Comienzo del primer * y final del último * en la fila, que se encarga de imprimir espacios en blanco alternados y *.
  • Caso 3: La estrella final esencialmente dice que imprima una nueva línea o finalice el programa si ya hemos terminado n filas.
    Consulte la imagen de abajo

A continuación se muestra la implementación del enfoque anterior:

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("  ");
          // Handles case 2
          else {
            if (flag)
            document.write("*");
            else
            document.write("  ");
 
            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>
Producción

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

Publicación traducida automáticamente

Artículo escrito por ssatyanand7 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *