Trebor
Trebor

Reputation: 5

In Java, how would I code a pyramid of asterisks by using nested for loops?

I am working on an assignment where I have to use nested loops to program a pyramid of asterisks that is on its side. The output of this program should look like this:

*    
**    
***    
**** 
***
**
*

When I run my program, it only displays the final four lines of the code. I don't know why the first three don't show up. Here is my code:

public class Main
{
    public static void main(String[] args) {

        for(int a = 0; a < 8; a++) //1
        {
            if(a < 4){
                for(int b = a; b < 4; b++)
                {
                    System.out.print("*");
                }

            }
            if(a >= 4)
                for(int c = a; c < 4; c++)
                {  
                    System.out.print("*");
                }

            System.out.println();
        } //loop 1

    }
}

And here is my output:

****
***
**
*

(There is some empty space after the output that I did not include. This is caused by the outer for loop iterating eight times.) How would I make my program correctly display all of the code, instead of just the last four lines?

Any help would be greatly appreciated.

Upvotes: 0

Views: 804

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28414

There are several mistakes in your logic:

  1. Since you only need 7 rows, the first loop should iterate until a < 7
  2. In the first 3 rows, your nested loop should iterate from 0 to a
  3. After that, the other nested loop should go from a to 7
  4. It is better to use if-else instead of two if statements

Here is the complete solution that I tested:

for(int a = 0; a < 7; a++) {
     if(a < 4){
          for(int b = 0; b <= a; b++)
               System.out.print("*");
     }else {
          for(int c = a; c < 7; c++)
               System.out.print("*");
     }
     System.out.println();
}

Output:

*
**
***
****
***
**
*

EDIT:

As mentioned in the comments, you can also split the outer loop into two parts in order to remove the conditions as follows:

for(int a = 0; a < 4; a++) {
     for(int b = 0; b <= a; b++)
          System.out.print("*");
     System.out.println();
}
for(int a = 4; a <= 7; a++) {
     for(int b = a; b < 7; b++)
          System.out.print("*");
     System.out.println();
}

Upvotes: 1

Nathan Relyea
Nathan Relyea

Reputation: 144

You're close. Try something like this:

int size = 4;

for(int line = 1; line < size * 2; line++) {
  if(line <= size) {
    for(int i = 0; i < line; i++) {
      System.out.print("*");
    }
  }
  else {
    for(int i = 0; i < size * 2 - line; i++) {
      System.out.print("*");
    }
  }
  System.out.println();
}

Upvotes: 0

Related Questions