Java - What is the output: for loop to create shape

Question

What is the output of the following code.

import java.util.Scanner;

public class Main {

  public static void printChars(String s, int n) {
    for (int i = 1; i <= n; i++) {
      System.out.print(s);
    }
  }

  public static void printSpaces(int n) {
    printChars(" ", n);
  }

  public static void printLastRow(int n) {
    printChars("*", n);
  }

  public static void printFirstRow(int rows) {
    printSpaces(rows - 1);

    System.out.println("*");
  }

  public static void printMiddleRows(int rows) {

    int outsideSpaces = rows - 2;
    int insideSpaces = 1;

    // loop over each row
    for (int i = 1; i <= rows - 2; i++) {

      printSpaces(outsideSpaces);
      System.out.print("*");
      printSpaces(insideSpaces);
      System.out.println("*");

      outsideSpaces--;
      insideSpaces += 2;
    }

  }

  public static void main(String[] args) {
    int rows = 10;
    printFirstRow(rows);
    printMiddleRows(rows);
    printLastRow(rows * 2 - 1);
  }
}


Click to view the answer

a shape

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

Demo

import java.util.Scanner;

public class Main {

  public static void printChars(String s, int n) {
    for (int i = 1; i <= n; i++) {
      System.out.print(s);/*from  w  w  w .j  a va  2s  .  c  o m*/
    }
  }

  public static void printSpaces(int n) {
    printChars(" ", n);
  }

  public static void printLastRow(int n) {
    printChars("*", n);
  }

  public static void printFirstRow(int rows) {
    printSpaces(rows - 1);

    System.out.println("*");
  }

  public static void printMiddleRows(int rows) {

    int outsideSpaces = rows - 2;
    int insideSpaces = 1;

    // loop over each row
    for (int i = 1; i <= rows - 2; i++) {

      printSpaces(outsideSpaces);
      System.out.print("*");
      printSpaces(insideSpaces);
      System.out.println("*");

      outsideSpaces--;
      insideSpaces += 2;
    }

  }

  public static void main(String[] args) {
    int rows = 10;
    printFirstRow(rows);
    printMiddleRows(rows);
    printLastRow(rows * 2 - 1);
  }
}

Related Quiz