Program to print pattern W of height N

Problem Statement

Given an integer N,our task is to output a pattern W of height N

Example:

input:N=3

 Output:    *              *

                   *      *      *

                   *              *

input:N=5 

Output:           *                          *

                         *                          *

                         *            *            *

                         *       *        *       *

                         *                          *           

Below is the Java implementation of the above approach:

Solution

Code 

import java.io.*;

class Solution {

public static void printPattern(int n)

{
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            // printing * in 1st and last column
             if (j == 1 || j == n) {
                    System.out.print("*\t");
                }
        // printing * in second half (either left or
        // right diagonal )
           else if (i > n / 2&& (i == j || i + j == n + 1)) {
                 System.out.print("*\t");
            }
            // otherwise print space
            else {
                System.out.print("\t");
            }
    }
    // new line        

      System.out.println();
    }
}
    public static void main(String[] args)
    {
        int n = 3;
        printPattern(n);
    }

Output:

*               *

*      *       *

*               *

Feel free to comment if you have any doubt in comments section 

For more Data structure and algorithms,computer science,programming,coding related problems search my website.


Learn how to prepare for Information Technology Based companies here 

 

Post a Comment

0 Comments