sunshineshak
sunshineshak

Reputation: 21

Write a java program that prints a pyramid of numbers using only a while loop

It needs to look like this:

It needs to look like this

I have a for loop code that works but I can't turn it into a correct while loop one.

Here is the for loop code:

public class NumPyramid {

    public static void main(String[] args) {

        int rows = 9;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= (rows - i) * 2; j++) {
                System.out.print(" ");
            }
            
            for (int k = i; k >= 1; k--) {
                System.out.print(" " + k); //create left half            
            }
            for (int l = 2; l <= i; l++) {
                System.out.print(" " + l); //create right half
            }
            
            System.out.println();
        }
    }
}

Upvotes: 0

Views: 1545

Answers (3)

Nowhere Man
Nowhere Man

Reputation: 19545

You may use a StringBuilder to hold the entire string you need to print and fill it with spaces.

For the initial step you set '1' into the middle and print the contents of the string. After that you "move" to the left and right, set the next i and repeat printing until all rows are done.

Update
Added space parameter to control the distance between digits in the pyramid.

int n = 9;
int i = 1;
int space = 2; // distance between two adjacent digits
int width = 2 * space * (n - 2) + 1; // 0 not included

StringBuilder sb = new StringBuilder();
while (i++ <= width) {
    sb.append(' ');  // prepare StringBuilder with whitespaces
}

i = 0;
int left = width / 2;
int right = width / 2;
while (i++ < n - 1) { // print 1..8
    sb.setCharAt(left, (char)(i + '0'));
    sb.setCharAt(right, (char)(i + '0'));
    System.out.println(sb);
    left -= space;
    right += space;
}

Upvotes: 0

sunshineshak
sunshineshak

Reputation: 21

This is what I did and it works!

  int rows = 9, i = 1;

   while (i <= rows)
    {
        int j = 1;
        while (j<=(rows-i)*2)
        {
            System.out.print(" ");
            j++;
        }
        int k = i;
        while (k >= 1)
        {
            System.out.print(" "+k);
            k--;
        }
        int l = 2;
        while (l<=i)
        {
            System.out.print(" "+l);
            l++;
        }
        System.out.println();
        i++;
    }

Upvotes: 2

Rubydesic
Rubydesic

Reputation: 3476

In general, this is how you convert a for loop to a while loop:

for (initial; condition; iterate) {
    statement;
}

becomes

initial;
while (condition) {
    statement;
    iterate;
}

Upvotes: 4

Related Questions