Java Program to Print Swastika Sign By Taking User Input
Take as input N, an odd number (>=5). Print the following pattern as given below for N = 7. Here the input format is the value of N and output results out in swastika pattern printing.
Illustration:
Input Format: Enter value of N ( >=5 )
Constraints: 5 <= N <= 99
Output Format: Print the required pattern.
* * * * *
* *
* *
* * * * * * *
* *
* *
* * * * *
Let us thinks of a way out in order to figure out by listing the logic prior to writing any code in order to generate the desired pattern.
Procedure:
- First, take an input (N) from the user.
- Initialize rows and cols as 1 to make loops in for the statement.
- In the first row, we definitely know we have to print a * then give some spaces till N/2, and then again print stars till N.
- In the second to N/2 rows, first, we need to print a * then spaces till N/2 (that it , we don’t need to provide spaces here)
- In the (N/2)+1 th row, just print * till N.
- Again in (N/2) +2th row to N -1, we need to first print spaces till N/2 and then print a * and the spaces till N-1 and finally a * at the end
- In the final row, we need to print * till (N/2) + 1 and then print spaces till N-1 now and then finally ending it a *.
- Lastly do not forget to add System.out.println() to add a blank line after each line of work
Now let us implement the some by writing the core for the same.
Example
Java
class GFG {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int rows = 1 ;
while (rows <= N) {
if (rows == 1 ) {
System.out.print( "*" );
for ( int csp = 1 ; csp < N / 2 ; csp++)
System.out.print( " " );
for ( int cst = (N / 2 ) + 1 ; cst <= N; cst++)
System.out.print( "*" );
System.out.println();
}
else if (rows <= N / 2 && rows > 1 ) {
System.out.print( "*" );
for ( int csp = 1 ; csp < N / 2 ; csp++)
System.out.print( " " );
System.out.print( "*" );
System.out.println();
}
else if (rows == (N / 2 ) + 1 ) {
for ( int cstt = 1 ; cstt <= N; cstt++)
System.out.print( "*" );
System.out.println();
}
else if (rows <= N - 1 && rows > (N / 2 ) + 1 ) {
for ( int csp = 1 ; csp <= N / 2 ; csp++)
System.out.print( " " );
System.out.print( "*" );
for ( int cspp = 1 + (N / 2 ); cspp < N - 1 ;
cspp++)
System.out.print( " " );
System.out.print( "*" );
System.out.println();
}
else {
for ( int csttt = 1 ; csttt <= (N / 2 ) + 1 ;
csttt++)
System.out.print( "*" );
for ( int csppp = (N / 2 ) + 2 ;
csppp <= N - 1 ; csppp++)
System.out.print( " " );
System.out.print( "*" );
}
rows++;
}
}
}
|
Output:
Note: One can also use BufferedReader class if you want to take input from user to enter the number of rows here.
Last Updated :
26 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...