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
#include<iostream>
#include<iomanip>
using namespace std;
void generatePattern( int n)
{
for ( int i=1 ; i<=n ; i++)
cout << setfill( ' ' ) << setw(n)
<< string(i, '*' ) << endl;
}
int main()
{
int n = 6;
generatePattern(n);
return 0;
}
|
Java
public class PatternPrinting {
public static void generatePattern( int n) {
for ( int i = 1 ; i <= n; i++) {
System.out.printf( "%" + n + "s%n" , "*" .repeat(i));
}
}
public static void main(String[] args) {
int n = 6 ;
generatePattern(n);
}
}
|
Python3
def generatePattern(n):
for i in range ( 1 , n + 1 ):
print ( str ( '*' * i).rjust(n))
if __name__ = = '__main__' :
n = 6
generatePattern(n)
|
C#
using System;
public class GFG {
public static void GeneratePattern( int n)
{
for ( int i = 1; i <= n; i++)
Console.WriteLine( "{0," + n + "}" , new String( '*' , i));
}
public static void Main()
{
int n = 6;
GeneratePattern(n);
}
}
|
Javascript
function generatePattern(n)
{
for (let i = 1; i <= n; i++) {
console.log( "*" .repeat(i).padStart(n));
}
}
const n = 6;
generatePattern(n);
|
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 GeeksforGeeks( 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.
Last Updated :
02 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...