static void k(){
Scanner sc= new Scanner(System.in);
System.out.println("no.of rows");
int a = sc.nextInt();
for(int row=a; row>=1; row--){
for (int col=1; col <=row-1; col ){
System.out.print(" * ");
}
System.out.println();
}
for(int row=1; row<=a; row ){
for (int col=1; col <=row-1; col ){
System.out.print(" * ");
}
System.out.println();
}
}
* * * *
* * *
* *
*
*
* *
* * *
* * * *
I am trying to print the above patterns in Java, but two extra lines are getting added between the patterns. I don't know how to remove them.
CodePudding user response:
Try this, ie inner loops without -1
for(int row=a; row>=1; row--){
for (int col=1; col <=row; col ){
System.out.print(" * ");
}
System.out.println();
}
for(int row=1; row<=a; row ){
for (int col=1; col <=row; col ){
System.out.print(" * ");
}
System.out.println();
}
CodePudding user response:
You will have to add some conditions to your System.out.println()
calls.
Also:
- Use appropriate variable/method names, avoid using single-letter names
- You should index at
0
; it makes more logical sense
public class Main {
public static void main(String[] args) {
printTriangles();
}
private static void printTriangles() {
//Scanner sc = new Scanner(System.in);
//System.out.print("Number of rows: ");
int rows = 4; // sc.nextInt();
for (int row = rows; row > 0; row--) {
for (int col = 0; col < row; col ) {
System.out.print(" * ");
}
if (row > 1) {
System.out.println();
}
}
for (int row = 0; row <= rows; row ) {
for (int col = 0; col < row; col ) {
System.out.print(" * ");
}
if (row < rows) {
System.out.println();
}
}
}
}
Output
Where input = 4
* * * * * * * * * * * * * * * * * * * *