Learn Programming through Logical Thinking Series – 10

Learn Programming through Logical Thinking Series – 10

This blog explains about Learn Programming through Logical Thinking Series – 10 and is given below : 

_______________________________________________________________________________

Hi,

In today’s post, we discuss about printing X pattern.  Already we know how to use looping statements in Java.  Here I am using while – nested while looping statements to derive X pattern.  The expected output is

X Pattern

Code:

public static void printCross(int size, char display)
{
    for (int row = 0; row < size; row++) {
        for (int col = 0; col < size; col++) {
            if (row == col || row + col == size - 1) {
                System.out.print(display);
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }
}

Output: 

(size = 5, display = 'x')

x   x
 x x 
  x  
 x x 
x   x

X Pattern Program

public class XPattern {
public static void main(String[] args) {
int i=0,j;
while(i<3){
j=0;
while(j<(i*1)){
System.out.print(” “);
j++;
}
int k=0;
while(k<=(i-i)){
System.out.print(“*”);
k++;
}
k=0;
while(k<(4-(2*i))){
System.out.print(” “);
k++;
}
k=0;
while(k<=(i*0)){
System.out.print(“*”);
k++;
}
System.out.println();
i++;

}
i=1;
while(i>=0){
j=0;
while(j<(i*1)){
System.out.print(” “);
j++;
}
int k=0;
while(k<=(i*0)){
System.out.print(“*”);
k++;
}
k=4;

while(k>(i*2)){
System.out.print(” “);
k–;
}
j=0;
while(j<=(i*0)){
System.out.print(“*”);
j++;
}

System.out.println();
i–;
}
}}

Output:

X Pattern

There are various programs to print X pattern using * 

// Java program to 
// print cross pattern 
class GFG
{
  
// Function to print given 
// string in cross pattern
static void pattern(String str,
                    int len)
{
      
    // i and j are the indexes 
    // of characters to be 
    // displayed in the ith 
    // iteration i = 0 intially 
    // and go upto length of string
    // j = length of string initially 
    // in each iteration of i, 
    // we increment i and decrement j,
    // we print character only 
    // of k==i or k==j
    for (int i = 0; i < len; i++)
    {
        int j = len - 1 - i;
        for (int k = 0; k < len; k++)
        {
            if (k == i || k == j)
                System.out.print(str.charAt(k));
            else
                System.out.print(" ");
        }
        System.out.println("");
    }
}
  
// Driver code
public static void main (String[] args)
{
    String str = "geeksforgeeks";
    int len = str.length();
    pattern(str, len);
  
}
}