I want to print the below pattern
v
v v
v v
v v
Below is the code which I have tried.
public static void main(String[] args) {
System.out.println("The Pattern is");
for (int i = 0; i < 4; i++) {
//System.out.println(i);
for (int k = 0; k <= i - 2; k++) {
System.out.print("v ");
}
for (int j = 0; j <= 4 - i; j++) {
System.out.print(" ");
}
System.out.println();
}
}
I'm getting the below output:
v
v v
Can anyone help me to solve this pattern?
Move the j loop before k loop
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("The Pattern is");
for(int i=0;i<4;i++) {
for(int j=0;j<=4-i;j++)
System.out.print(" ");
for(int k=0;k<=i-2;k++)
System.out.print("V ");
System.out.println();
}
}
Another way to do the job (dynamic number of rows):
public static void main(String[] args) {
final int numRows = 4;
for (int row = 0; row < numRows; row++) {
for (int preSpace = numRows - row; preSpace >= 0; preSpace--) {
System.out.print(" ");
}
if (row > 0) {
System.out.print("v");
for (int postSpace = 1; postSpace < row * 2; postSpace++) {
System.out.print(" ");
}
}
System.out.println("v");
}
}
The following code will print it
public static void main(String[] args) {
System.out.println("The Pattern is");
// startup parameter
final int rowSize = 4;
final int startPos = 2;
int leftPos = startPos;
int rightPos = startPos;
// for each row
for(int row=0; row<rowSize; row++){
// find and print v (max is right most v)
for(int col=0; col<rightPos+1; col++){
// when reach left pos
if(col==leftPos){
System.out.print("v");
// when left pos and right pos is same
if(leftPos==rightPos){
break;
}
}
// when reach right pos
if (col==rightPos){
System.out.print("v");
break;
}
// print space when it is not match
System.out.print(" ");
}
// next line
System.out.println();
// adjust position
if(leftPos!=0) leftPos--;
rightPos++;
}
}
This works for me:
public class DrawPattern {
public static void main(String[] args) {
int i, j;
int num = 7;
for (i = 0; i < num; i++) {
for (j = 0; j < num; j++) {
if (isConditionMatch(num, i, j)) {
System.out.print("V");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
// this pattern will decide where to print 'V'
private static boolean isConditionMatch(int num, int i, int j) {
return (i + j == (num - 1) / 2 || j - i == (num - 1) / 2);
}
}
Output:
V
V V
V V
V V
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.