Print X Pattern In Java
JAVA Programming Language Java Loops

Print X Pattern In Java

In this article, we are going to teach you how to Print X Pattern In Java. So, let’s start creating the program.

Print X Pattern In Java:

We are using simply a Nested for a loop both the loops iterate from 1 to n(the number entered by the user). In the inner loop, we are using an if-else statement.

The condition is if(i==j || i+j==8) then print the stars else print spaces. The logic of i+j is that suppose that the matrix or in the grid where the sum of i+j =8 (that is the cells of the grid or matrix) if the sum is equal to 8 then print stars and else print the spaces. For n=7 we use this logic if u take the value of n =4 then you will give the condition to the compiler if( i==j || i+j==5) so, give the condition according to your program

Source Code:

import java.util.*;
public class pattern
{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number :");
        int n = sc.nextInt();//n=7//
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if ( i == j || i+j==8) {
                    System.out.print("*");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}

Print X Pattern In Java
Print X Pattern In Java

 

 

 

 

 

 

Output:

Above image is the required output that is a X pattern and from the above program we conclude that how to write a program to print Print X Pattern In Java.

Check our previous article that is Mirror Inverted Reverse Triangle In Java Without Using a Single Function.

Leave a Reply

Your email address will not be published. Required fields are marked *