Example
Input
5
Output
*****
* *
* *
* *
*****
Required to Know
Use of Variables, Use of different operators like assignment or arithmetic operators, Use of methods like System. out. print(), and use of for loop, use of nested for loop, and Use of Data types
Steps
Take range as input from the user.
Run the outer loop till the given range. Inside the outer loop, we also need to run another loop till the given range only.
Inside the another loop, we need to provide a condition to print the star in each column of a row.
In the outer loop which is the main loop also, we need to use the next line statement. So that it moves to the next line.
How the loop should be structured along with the condition
Outer loop : - for(i=1;i<=n;i++) -> rows
Inside the outer loop : - for(j=1;j<=n;j++) -> columns
Condition : - if(i==1 || i==n || j==1 || j==n)
i==1 or i==n means : - first row and last row
j==1 or j==n means : - first column and last column
Print star statement : - System.out.print("*");
Print star in the next line statement : - System.out.println(" ")
Program
import java.util.Scanner;
public class Mavenproject1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, n;
int j;
n = sc.nextInt();
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
if(i==1 || i==n || j==1 || j==n){
System.out.print("*");
}
else{
System.out.print(" ");
}
}
System.out.println(" ");
}
}
}