DaniWeb IT Discussion Community

Code Snippets (http://www.daniweb.com/code/)
-   cplusplus (http://www.daniweb.com/code/cplusplus.html)
-   -   Pascal Triangle Generator (http://www.daniweb.com/code/snippet803.html)

darkscript cplusplus syntax
Jan 10th, 2008
This program generates lines of pascal's triangle, numbers after 23 generate weird output.

  1. #include <iostream>
  2. #include <stdlib.h>
  3.  
  4. using namespace std;
  5.  
  6. string Separator(" ");
  7.  
  8. float factorial (float n)
  9. {
  10. if (n == 0.0f)
  11. return 1.0f;
  12. else if (n != 1.0f)
  13. return n*factorial (n-1.0f);
  14. else
  15. return n;
  16. }
  17. float combination (float n,float r)
  18. {
  19. return factorial(r)/((factorial(r-n)*factorial(n)));
  20. }
  21.  
  22. void printRow(float r)
  23. {
  24. for (float i=0.0f; i<=r; i+=1.0f){
  25. cout << combination (i,r) << Separator;
  26. }
  27. }
  28.  
  29. void printRows(float r)
  30. {
  31. for (float j=0.0f; j<r; j+=1.0f){
  32. printRow(j);
  33. cout << endl;
  34. }
  35. }
  36. int main(int argc, char** argv)
  37. {
  38. float nRows = 10.0f;
  39. cout << "Hello, This is me Pascal. I'll give you ";
  40. if (argv [1] == 0)
  41. cout << "10 Lines of my famous triangle";
  42. else if (atof (argv [1]) <= 0.0f)
  43. cout << "10 Lines of my famous triangle";
  44. else {
  45. nRows = atof(argv [1]);
  46. cout << argv [1] << (nRows > 1? " Lines " : " Line ") << "of my famous triangle.\n";
  47. }
  48. printRows(nRows);
  49. }