Tuesday 16 February 2016

Java: Draw a hollow Rectangle java program.

Problem: Hollow Rectangle

Draw a hollow rectangle of given height & width.
Sample Input:
height :  4
width  :  5

Sample Output:

12345
1      5
1      5
12345

Solve:
Lets see the following Code:
// ADLabs

import java.util.Scanner;

public class NastedForLoop {

 public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);
  System.out.print("Enter height:");
  int row = sc.nextInt();
  System.out.print("Enter width:");
  int col = sc.nextInt();
  System.out.println();

  // Hollow Rectangle

  for (int i = 1; i <= row; i++) {

   for (int j = 1; j <= col; j++) {

    if (i == 1 || i == row) {
     System.out.print(j);
    } else if (j > 1 && j < col) {
     System.out.print(" ");
    } else
     System.out.print(j);

   }
   System.out.println();
  }

  sc.close();
 }

}




Console:

Enter height: 4
Enter width: 5

12345
1      5
1      5
12345

Happy Coding :)
-@D