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 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; } |
Output:
*
**
***
****
*****
******
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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks 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.
Recommended Posts:
- Print a pattern without using any loop
- Print the pattern by using one loop | Set 2 (Using Continue Statement)
- std::setbase, std::setw , std::setfill in C++
- Print 1 to 100 in C++, without loop and recursion
- How will you print numbers from 1 to 100 without using loop?
- iomanip setw() function in C++ with Examples
- Print a character n times without using loop, recursion or goto in C++
- Print a number 100 times without using loop, recursion and macro expansion in C?
- Program to print pattern
- Program to print the pattern ‘D’
- Program to print the pattern "GFG"
- Print the given pattern recursively
- Program to print the pattern 'G'
- Program to print the given H Pattern
- Pattern to print X in a rectangular box

