Print a String in wave pattern in C++


In this problem, we are given a string and an integer n. Our task is to print the given string in a wave pattern of n lines.

Let’s take an example to understand the problem,

Input: Tutorial n = 3
Output:
T             r
   U       o       i       s
      t                l

Wave patterns are printed by printing each character of the string one by one in the next line and tab space away from the next element till the nth line. And the printing tab spaces to the upper line till the first line and follow the same pattern until the string has characters.

Example

The below code gives the implementation of our solution,

 Live Demo

#include<bits/stdc++.h>
using namespace std;
void printWavePattern(string s, int n) {
   if (n==1) {
      cout<<s;
      return;
   }
   int len=s.length();
   char a[len][len]={ };
   int row=0;
   bool down;
   for (int i=0; i<len; i++) {
      a[row][i]=s[i];
      if (row==n-1)
         down=false;
      else if (row==0)
         down=true;
         (down)?(row++):(row--);
   }
   for (int i=0; i<n; i++) {
      for (int j=0; j<len; j++) {
         cout<<a[i][j]<<" ";
      }
      cout<<endl;
   }
}
int main() {
   string str = "TutorialsPoint";
   int n = 4;
   cout<<n<<" Line wave pattern '"<<str<<"' is:\n";
   printWavePattern(str, n);
}

Output

4 Line wave pattern 'TutorialsPoint' is −
T    a    n
u   i l    i t
t    r    s o
   o    P

Updated on: 22-Jan-2020

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements