programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Pascal's Triangle Recursive/Nonrecursive Help

Greenhorn
Posts: 6
• Number of slices to send:
Optional 'thank-you' note:
I need to create a program that creates a Pascal's Triangle based on a given n value, and place it into a 2D Array, and print it to the screen. I've been having a little trouble with my methods. For example, if n = 5 and k = 3, then the output should be like:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

PascalArray test = new PascalArray();
test.pascalNonRecursive(5); //GIVES ME 1121331464 as output
System.out.print(test.pascalRecursive(4, 2); //GIVES ME 6 as output

How can I fix (and refine) my code? I obviously need a lot of help, and I will really appreciate anything you give me. Thanks a lot!

Ranch Hand
Posts: 234
• Number of slices to send:
Optional 'thank-you' note:

System.out.print(test.pascalRecursive(4, 2); //GIVES ME 6 as output

What did you expect? 3?
I think the method works correct, the value at position 4, 2 is indeed 6. This is because you have put

Because you have put width==0 you start counting at zero. If you want starting counting at one you should put

For the non-recursive one, you have a similar problem.

When k is zero, the second for loop doesn't run "r=0; r<k" and for the next values, it will always omit the last run.
You need there for(int r=0; r<=k; r++) to make it work
(When you put an System.out.println(""); after the inner for loop, you get a nicely formatted output )
[ October 29, 2007: Message edited by: bart zagers ]

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.