
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
#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
Advertisements