Program to print a string in vertical zigzag manner | C ++ program for the above approach ; Function to print any string in zigzag fashion ; Store the gap between the major columns ; Traverse through rows ; Store the step value for each row ; Iterate in the range [ 1 , N - 1 ] ; Print the character ; Print the spaces before character s [ j + step ] ; Print the character ; Print the spaces after character after s [ j + step ] ; Print the spaces for first and last rows ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void zigzag ( string s , int rows ) { int interval = 2 * rows - 2 ; for ( int i = 0 ; i < rows ; i ++ ) { int step = interval - 2 * i ; for ( int j = i ; j < s . length ( ) ; j = j + interval ) { cout << s [ j ] ; if ( step > 0 && step < interval && step + j < s . length ( ) ) { for ( int k = 0 ; k < ( interval - rows - i ) ; k ++ ) cout << " ▁ " ; cout << s [ j + step ] ; for ( int k = 0 ; k < i - 1 ; k ++ ) cout << " ▁ " ; } else { for ( int k = 0 ; k < ( interval - rows ) ; k ++ ) cout << " ▁ " ; } } cout << endl ; } } int main ( ) { string s = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh " " ijklmnopqrstuvwxyz " ; int rows = 9 ; zigzag ( s , rows ) ; }