Print the asterisk in diamond shape using java

This is the one of interview question, I've been faced.

Need to print the asterisks in diamond shape. That's a rule.

         *
       *  *
     *  *  *
  *  *   *   *
    *   *   *
       *  *
         *

Like above.

Solution:

import java.util.Scanner;

public class PrintAsterisks {

    public static void main(String[] args) {
        System.out.print("Enter the number of rows : ");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        for (int i = 1; i <= num; i++) {
            for (int j = num; j >= i; j--) {
                System.out.print(" ");
            }
            for (int m = 1; m <= i; m++) {
                System.out.print(" *");
            }
            System.out.print("\n");
        }
        for (int i = 1; i <= num; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(" ");
            }
            for (int m = num-1; m >= i; m--) {
                System.out.print(" *");
            }
            System.out.print("\n");
        }
    }
}

Comments

Popular posts from this blog

Flutter Bloc - Clean Architecture

Dependencies vs Dev Dependencies in Flutter

What's new in android 14?