Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a complete program that has the following Write a nested for loop that pri

ID: 3626178 • Letter: W

Question

Write a complete program that has the following
Write a nested for loop that prints the following output:

                         1
                       1 2 1
                     1 2 4 2 1
                  1 2 4 8 4 2 1
              1 2 4 8 16 8 4 2 1
         1 2 4 8 16 32 16 8 4 2 1
    1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

Hint: Here is the psudocode solution:

for row from 0 to 7 {
pad leading blanks in a row like this
for the column from 1 to 7-row:
print a set of spaces
print left half of row
for column from 0 to row:
print spaces followed by 2 raised to the power of the column
print right half of row
for column from row-1 to 0:
print spaces followed by 2 raised to the power of the column
print a new line

You need to figure out how many spaces to print before the number. The simple way to compute powers of 2 is with the Math.pow function; can you do this without it?

Explanation / Answer


public class Pyramid {
   
    // print number with enough whitespace in front of it
    // to make a column of width 5
    public static void printNumberInColumn(int n) {
        // (int) Math.log10(n) equals the number of digits in n, minus 1.
        // The number of spaces will be 5 minus the number of digits
        // which equals 4 minus Math.log10(n)
        for (int m=0; m < 4 - ((int) Math.log10(n)); m++) {
            System.out.print(" ");
        }
        System.out.print(n);
    }

    public static void main(String[] args) {
        for (int row=0; row<=7; row++) {
            // Print leading whitespace
            for (int col=0; col <= 7-row; col++) {
                System.out.print("     ");
            }
            int number = 1;
            // Print columns up to the midline
            for (int col=0; col<=row; col++) {
                printNumberInColumn(number);
                number = number * 2;
            }
            number = number / 2; // after this, number equals the peak of the row
            // Print columns after the midline
            for (int col = row-1; col >= 0; col--) {
                number = number / 2;
                printNumberInColumn(number);
            }
            // Start a new line
            System.out.println();
        }

    }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote