Print Zig Zag Number Pattern
In the previous article, we have discussed Java Program to Print Window Number Pattern
In this article we will see how to print zig-zag number pattern.
Example: Enter the no of characters in a line = 3 Enter the no of zig zag line = 4 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.
Approach :
- Print one backward slash first then one forward slash and continue.
- Enter total characters in a row and store it an integer variable say
row
. - Enter total no. of zig zag lines and store in an integer variable say
count
. - To print Backward slash :
- Take first for loop to print all the rows.
- Take a inner loop to print the column values.
- Then go on printing the numbers according to the iteration.
- To print forward slash :
- Take first for loop to print all the rows.
- Take inner loop to print the column values.
- Then go on printing the numbers according to the iteration.
Java Code to Print Zig Zag Number Pattern
import java.util.Scanner; public class Main { public static void main(String[] args) { // Take user input for no fo rows System.out.print("Enter the no of characters in a line = "); Scanner sc= new Scanner(System.in); int r,c,row; //starting ASCII value taken 64 int ascii=64; // store the input value in row row=sc.nextInt(); System.out.print("Enter the no of zig zag line = "); int count=sc.nextInt(); for (int i=1;i<=count;i++) { // backward for(r=1; r<=row; r++) { // inner loop to print number for(c=1; c<=row; c++) { // if row and column have same value print symbol if(r==c) System.out.print(r+" "); else System.out.print(" "); } System.out.println(""); } // forward for(r=1;r<=row;r++) { // loop for printing number for(c=1;c<=row;c++) { // if c<= row+1-r print symbol else spaces if(c <= (row+1-r)) { if( c == (row+1-r) ) System.out.print(r+" "); else System.out.print(" "); } } System.out.println(""); } } } }
Output: Enter the no of characters in a line = 3 Enter the no of zig zag line = 4 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.
Related Java Number Pattern Programs: