Java Program to Draw a Rectangle using For loop
ADVERTISEMENTS
Java program to draw a rectangle using for loop. In this article, you will learn how to draw a rectangle in java using for loop.
Source Code
// Java Program to Draw a Rectangle using For loop
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int r = 0, c = 0, i, j;
// r - denotes the number of rows
// c - denotes the number of columns
System.out.println("-----Enter the number of rows & columns-----");
r = in.nextInt();
c = in.nextInt();
for (i = 1; i <= r; i++) {
for (j = 1; j <= c; j++) {
if (i == 1 || i == r || j == 1 || j == c)
System.out.print("* ");
else
System.out.print(" ");
}
System.out.print("\n");
}
}
}
Output
-----Enter the number of rows & columns-----
6
14
* * * * * * * * * * * * * *
* *
* *
* *
* *
* * * * * * * * * * * * * *
6
14
* * * * * * * * * * * * * *
* *
* *
* *
* *
* * * * * * * * * * * * * *