So I had a little bit of a challenge question for my AP Computer Science class. It's due tomorrow, and I still can't figure it out for the life of me.
Draw Pascal's Triangle, using System.out.printf. The program requests how many rows of the triangle you want, and it prints it out in a nice triangular format. I'm struggling with JAVA, and an explanation would be very, very much appreciated.
We're only two months into the school year, so bear with me. Thanks in advance :).
Okay, I've worked out the algorithm (actually quite proud, did it in 10 mins at 12:15am after 3 bottles of ale and I had no idea what Pascals Triangle was up until now!) and it all works well, I just haven't done the printf's. I'm sure you can work out the formatting though ;)
Step by step guide for the algorithm:
- Create a 2d array who's length is the amount of rows you want. I shall refer to it as 'triangle'.
- Each element in the array is another array of length rowNumber + 1. This will give you a triangle shaped array
- Use a for loop to iterate over the rows in the 'triangle' array. Check to see if you are on row 0. Set the value at row=0 and col=0 to 1.
- If you are at a row > 0, check you are not at column 0. If you are at col>0, add 'triangle[row-1][col-1] to the value at the current row and column. This adds the value above-left to the current value.
- Check to see if you are at the end of the row. If you are col<triangle[row].length-1 (i.e not at the end of the row) then add 'triangle[row-1][col]' to the value at the current row and col. This is adding the value above-right.
- End col for loop and row for loop.
- Print out all values appropriately.
I hope that helps. If it doesn't, here is my code: http://pastebin.com/6d2yqmKm
Now off to bed!
As simple as it may look, there are still yet some things I haven't learned yet in the code posted :/.
This is what one of my friends came up with. I'm still struggling on how they come up with the for loops and equations to get the right numbers :/