Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

help with java

  • 17-10-2008 06:23PM
    #1
    Registered Users, Registered Users 2 Posts: 788 ✭✭✭


    For this program I need to output Pascals Triangle but print a star ‘x’ for the odd numbers and a space (‘ ‘) for the even numbers instead. I'm not sure how to do this :s Can anyone help?
    public class Pascals {
      
        public static void main(String[] args) {
    
            String[] line = new String[10];
            long[][] rows = new long[10][];
            for (int i = 0; i < rows.length; i++)
            {
                rows[i] = new long[i + 1];
    
                // Outer entries are equal to 1
                rows[i][0] = 1;
                rows[i][rows[i].length - 1] = 1;
    
                // If you're on the second or subsequent row...
                if (i > 0)
                {
                    //Add the bits in the middle
                    for (int j = 1; j < rows[i].length - 1; j++)
                    {
                        rows[i][j] = rows[i - 1][j - 1] + rows[i - 1][j];
                    }
                }
            }
            
            for (int i = 0; i < 10; i++)
            {
                line[i] = "";
                for (int j = 0; j < rows[i].length; j++)   
                {
                    line[i] = line[i] + rows[i][j] + " ";             
                }
            }
            
            // largest line is last line
            int largest = line[9].length();
            // print back the lines
            for(int i = 0; i < 10; i++) {
                // number of white spaces
                int nbSpace = largest - (line[i].length()) / 2;
                for(int j = 0; j < nbSpace; j++)              
                    System.out.print(" ");
                System.out.println(line[i]);
            }
        }
    


Comments

Advertisement