Program to print a string in vertical zigzag manner | Java 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
public class GFG { static 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 ) { System . out . print ( s . charAt ( j ) ) ; if ( step > 0 && step < interval && step + j < s . length ( ) ) { for ( int k = 0 ; k < ( interval - rows - i ) ; k ++ ) System . out . print ( " ▁ " ) ; System . out . print ( s . charAt ( j + step ) ) ; for ( int k = 0 ; k < i - 1 ; k ++ ) System . out . print ( " ▁ " ) ; } else { for ( int k = 0 ; k < ( interval - rows ) ; k ++ ) System . out . print ( " ▁ " ) ; } } System . out . println ( ) ; } } public static void main ( String args [ ] ) { String s = "123456789ABCDEFGHIJKLM " + " NOPQRSTUVWXYZabcdefghi " + " jklmnopqrstuvwxyz " ; int rows = 9 ; zigzag ( s , rows ) ; } }