Saturday, September 21, 2024
Google search engine
HomeData Modelling & AIPrint pattern using only one loop | Set 1 (Using setw)

Print pattern using only one loop | Set 1 (Using setw)

Print simple patterns like below using single line of code under loop. 
Examples:

Input : 5
Output :
    *
   **
  ***
 ****
*****

Input : 6
Output :
     *
    **
   ***
  ****
 *****
******

setw(n) Creates n columns and fills these n columns from right. We fill i of them with a given character, here we create a string with i asterisks using string constructor. setfill() Used to set fill character in a stream. Here we use it to fill remaining n-i-1 places with space (or ‘ ‘) in n columns. 

CPP




// CPP program to print a pattern using only
// one loop. <iomanip> is header file for stfill()
// and setw()
#include<iostream>
#include<iomanip>
using namespace std;
 
void generatePattern(int n)
{
    // Iterate for n lines
    for (int i=1 ; i<=n ; i++)
        cout << setfill(' ') << setw(n)
            << string(i, '*') << endl;
 
    // Remove multi-line commenting characters below
    // to get PATTERN WITH CHARACTERS IN LEFT AND
    // SPACE IN RIGHT
    /* for (int i=1 ; i<=n ; i++)
        cout << left << setfill(' ')
            << setw(n) << string(i,'*') << endl; */
}
 
// Driver code
int main()
{
    int n = 6;
    generatePattern(n);
    return 0;
}


C#




// C# program to print a pattern using only
// one loop. System namespace is used for Console
// class.
using System;
 
public class GFG {
public static void GeneratePattern(int n)
{
// Iterate for n lines
for (int i = 1; i <= n; i++)
Console.WriteLine("{0," + n + "}", new String('*', i));
      // Remove multi-line commenting characters below
    // to get PATTERN WITH CHARACTERS IN LEFT AND
    // SPACE IN RIGHT
    /* for (int i=1 ; i<=n ; i++)
        Console.WriteLine("{0,-" + n + "}", new String('*', i)); */
}
 
// Driver code
public static void Main()
{
    int n = 6;
    GeneratePattern(n);
}
}


Python3




#Python equivalent
#include <iostream> is replaced by print() function
#include <iomanip> is replaced by string.ljust()
 
def generatePattern(n):
    # Iterate for n lines
    for i in range(1, n+1):
        print(str('*'*i).rjust(n))
 
    # Remove multi-line commenting characters below
    # to get PATTERN WITH CHARACTERS IN LEFT AND
    # SPACE IN RIGHT
    '''for i in range(1, n+1):
        print(str('*'*i).ljust(n))'''
 
# Driver code
if __name__ == '__main__':
    n = 6
    generatePattern(n)


Javascript




// JS program to print a pattern using only
// one loop.
function generatePattern(n)
{
 
  // Iterate for n lines
  for (let i = 1; i <= n; i++) {
    console.log("*".repeat(i).padStart(n));
  }
 
  // Remove multi-line commenting characters below
  // to get PATTERN WITH CHARACTERS IN LEFT AND
  // SPACE IN RIGHT
  /*
  for (let i = 1; i <= n; i++) {
    console.log("*".repeat(i).padEnd(n));
  }
  */
}
 
// Driver code
const n = 6;
generatePattern(n);
 
// This code is contributed by akashish__


Output:

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

Time complexity: O(n2) for given input n
Auxiliary space: O(1)

Please refer below post for one more approach. Print pattern using only one loop | Set 2 (Using Continue) This article is contributed by Sakshi Tiwari. If you like neveropen( We know you do! ) and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments