Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Number Pyramid

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
        }

    }
}

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading