Created
October 25, 2020 19:02
-
-
Save aniruddha84/a53db00f2ead5a4d52f9eb0303be2272 to your computer and use it in GitHub Desktop.
ZigZag printer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ZigZag{ | |
public static void main(String []args){ | |
String str = "thisisazigzag"; | |
System.out.println(str); | |
printZigZag(str, 4); | |
} | |
public static void printZigZag(String input, int levels) { | |
char[][] charMatrix = new char[levels][input.length()]; | |
for(int i = 0; i < levels; i++) { | |
for(int j = 0; j < input.length(); j++) { | |
charMatrix[i][j] = ' '; | |
} | |
} | |
int rowNum = 0; | |
int colNum = 0; | |
int increment = 1; | |
for(int i = 0; i < input.length(); i++) { | |
colNum = i; | |
charMatrix[rowNum][colNum] = input.charAt(i); | |
rowNum += increment; | |
if (rowNum >= levels) { | |
rowNum = levels - 2; | |
increment = -1; | |
} else if (rowNum < 0) { | |
rowNum = 1; | |
increment = 1; | |
} | |
} | |
for(int i = 0; i < levels; i++) { | |
for(int j = 0; j < input.length(); j++) { | |
System.out.print(charMatrix[i][j]); | |
} | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment