- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ZigZag Conversion in C++
Suppose the string is like " IWANTTOLEARNCODE". This string is written in a zigzag way on a given number of rows say n. So the pattern is looking like this
I | T | A | O | |||
W | N | O | E | R | C | D |
A | L | N | E |
When we read the line like − "ITAOWNOERCDALNE"
So we have to create one module that can perform this kind of operation by taking the string and the number of rows.
To solve this, we will follow these steps
- when n = 1, then return s
- create an array of strings arr of size n
- row := 0, and down := true
- for i in range 0 to size of string – 1
- insert s[i] at the end of string arr[row]
- if row = b – 1, then down := false, otherwise when row= 0, then down := true
- if down is true, then increase row by 1, otherwise decrease row by 1
- ans := blank string
- for i in range 0 to n – 1:
- ans := ans + arr[i]
- return ans
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: string convert(string s, int numRows); }; string Solution::convert(string a, int b) { if(b == 1)return a; string arr[b]; int row = 0; bool down = true; for(int i = 0; i < a.size(); i++){ arr[row].push_back(a[i]); if(row == b - 1) down = false; else if(row == 0)down = true; if(down) row++; else row--; } string ans = ""; for(int i = 0; i < b; i++){ ans += arr[i]; } return ans; } main(){ Solution ob; cout << ob.convert("IWANTTOLEARNCODE", 3); }
Input
"IWANTTOLEARNCODE" 3
Output
"ITECWNTLANOEAORD"
- Related Articles
- Zigzag Iterator in C++
- ZigZag Tree Traversal in C++
- Zigzag (or diagonal) traversal of Matrix in C++
- Print a given matrix in zigzag form in C++
- Longest ZigZag Path in a Binary Tree in C++
- Conversion constructor in C++?
- Conversion Operators in C++
- Type Conversion in C++
- Bool to int conversion in C++
- Prefix to Postfix Conversion in C++
- Prefix to Infix Conversion in C++
- What is Type conversion in C#?
- Path In Zigzag Labelled Binary Tree in Python
- Binary Tree Zigzag Level Order Traversal in Python
- Decrease Elements To Make Array Zigzag in Python

Advertisements