HomeSoftware DevelopmentMake an ideal Pyramid by printing letters of a given String

# Make an ideal Pyramid by printing letters of a given String

Given a string str, the duty is to print an ideal pyramid by printing the characters of the given string.

Examples:

Enter: str =  “GEEKSFORGEEKS”
Output:
G
E  E  Okay
S  F  O  R  G

not together with  E Okay S as a result of they make our pyramid imperfect. i.e.

G
E  E  Okay
S  F  O  R  G
E  Okay  S

Enter: str = “PyramidOfStrings”
Output:
P
y  r  a
m  i  d  O  f
S  t   r   i   n  g   s

Method: To unravel the issue observe the above thought:

• Discover the rows as much as which an ideal pyramid could be made.
• After discovering the rows and variety of parts used within the string, implements the nested loop until that row.
• Take a pointer that traverses the string and prints the next character.

Beneath are the steps for the above method:

• Initialize a variable say n to retailer the size of the string.
• Initialize two variables x and ele, the place x will retailer the variety of parts in a selected row and ele will retailer the variety of whole parts used from string until that row as much as that row.
• Initialize variable rows as much as which the outer loop will run.
• There are 2 internal loops one for printing the beginning areas of each row and one other row for printing the character.
• Take a pointer ch that traverses the string and prints the next character.
• In each nth row there are 2*row-1 parts So print the character in a row till ok != 2*row-1.

Beneath is the implementation of the above method:

## C++

 #embody utilizing namespace std;    void perfectPyramid(string str) {             int n = str.size();                  int x = 1;                  int ele = 1;             int rows = 0;                  whereas (ele <= n) {         x += 2;         ele += x;         rows++;     }             int ch = 0;                  for (int i = 1, ok = 0; i <= rows; ++i, ok = 0) {                              for (int area = 1; area <= rows - i; ++area) {             cout << "  ";         }                              whereas (ok != 2 * i - 1) {             cout << str[ch] << " ";             ++ok;             ch++;         }         cout << endl;     } }    int important() {        string str = "PyramidOfStrings";             perfectPyramid(str);        return 0; }
Output

P
y r a
m i d O f
S t r i n g s

Time Complexity: O (rows*x),  the place rows are the full variety of rows and x is the full variety of parts in a selected row.
Auxiliary Area: O(1)

RELATED ARTICLES