Java Program For Printing 180 Degree Rotation of Simple Half Left Pyramid
Last Updated :
22 Sep, 2023
We can utilize ‘for’ and ‘while’ loops to print a 180-degree rotation of a simple half-left pyramid in Java as follows:
Example of 180-degree Rotation of Simple Half-Left Pyramid
Rows = 5
Output :
*
* *
* * *
* * * *
* * * * *
Methods For Printing 180-Degree Rotation of Simple Half-Left Pyramid
There are certain methods to Print the 180-rotated Simple Half-Left Pyramid mentioned below:
- Using a ‘for’ loop
- Using a ‘while’ loop
1. Using a ‘for’ loop
In this approach two for loops are utilized where, the first for loop identifies the number of rows while the second for loop identifies a number of columns. Here the values will be altered according to the first for loop. If j is greater than i then it will print the output otherwise it will print the space.
Below is the implementation of the above method:
Java
public class PyramidRotation {
public static void main(String[] args) {
int rows = 5 ;
for ( int i = 0 ; i < rows; i++) {
for ( int j = 0 ; j < rows - i - 1 ; j++) {
System.out.print( " " );
}
for ( int k = 0 ; k <= i; k++) {
System.out.print( "* " );
}
System.out.println();
}
}
}
|
Output
*
* *
* * *
* * * *
* * * * *
2. Using a ‘while’ loop
Explanation: The while loop checks for the condition until the condition becomes false. If the condition is true then it enters into the loop and executes the statements
Below is the implementation of the above method:
Java
public class PyramidRotation {
public static void main(String[] args) {
int i = 0 , j = 0 , sp = 0 ;
int rows = 5 ;
while (i < rows) {
while (sp < (rows - i - 1 )) {
System.out.print( " " );
sp++;
}
sp = 0 ;
while (j <= i) {
System.out.print( "* " );
j++;
}
j = 0 ;
i++;
System.out.println();
}
}
}
|
Output
*
* *
* * *
* * * *
* * * * *
Complexity of the above method
Time complexity: O(n2) for given input of ‘n’ rows
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...