Home > OS >  Java Number Pyramid
Java Number Pyramid

Time:03-24

I want to create a number pyramid like this,

      7
    5 6 5
  3 4 5 4 3 
1 2 3 4 3 2 1

but I couldn't create it. I pasted my code and its output is like this,

            7
        5 6 7 6 5
    3 4 5 6 7 6 5 4 3
1 2 3 4 5 6 7 6 5 4 3 2 1

What should I do to fix this ? Is my code totally wrong or litte changes are enough ?

import java.util.Scanner;
public class App {
    public static void main(String[] args){

        Scanner myScan = new Scanner(System.in);
        System.out.print("Enter mountain width: ");
        int width = myScan.nextInt();
        System.out.println("Here is your mountain ");
        myScan.close();
        System.out.println();

        for (int i = width; i >= 1; i=i-2)
        {
            for (int j = 1; j <= i*2; j  )
            {
                System.out.print(" ");
            }
 
            for (int j = i; j <= width; j  )          
            {
                System.out.print(j " ");
            }
 
            for (int j = width-1; j >= i; j--)
            {               
                System.out.print(j " ");            
            }

            System.out.println();
        }

    }
}

CodePudding user response:

You may compute the row index, then it's easy to get the number ranges

for (int i = width; i >= 1; i -= 2) {
    int row_idx = (width - i) / 2;
    for (int j = 1; j <= i; j  ) {
        System.out.print(" ");
    }
    for (int j = i; j <= i   row_idx; j  ) {
        System.out.print(j   " ");
    }
    for (int j = i - 1   row_idx; j >= i; j--) {
        System.out.print(j   " ");
    }
    System.out.println();
}

CodePudding user response:

You just need to count the level. You can do this by adding additional count variable. Lets take an example:

  1. On level 0 you just print 7 and count is 0.
  2. On level 1 count is 1. So you need to only print from i's current value count amount on left and right. But since we counted 1 extra on left so a value will be less on right.

......... And code will go on like this.

See code for better explanation:

public static void main( String[] args ) {

        Scanner myScan = new Scanner(System.in);

        System.out.print("Enter mountain width: ");

        int width = myScan.nextInt();

        System.out.println("Here is your mountain ");

        myScan.close();

        System.out.println();

        int counter = 0;

        for (int i = width; i >= 1; i = i - 2) {

            for (int j = 1; j <= i; j  ) {
                System.out.print(" ");
            }

            for (int j = i; j <= width - counter; j  ) {
                System.out.print(j   " ");
            }

            for (int j = width - 1 - counter; j >= i; j--) {
                System.out.print(j   " ");
            }

            System.out.println();

            counter  ;
        }
    }

I just changed a little bit on your code to make it work. Cheers mate !

  • Related