fork download
  1. //
  2. // main.cpp
  3. // Pascal Triangle
  4. //
  5. // Created by Himanshu on 20/09/21.
  6. //
  7.  
  8. #include <iostream>
  9. using namespace std;
  10.  
  11.  
  12. void printPascalTriangle (int n) {
  13. int pascal[n+1][n+1];
  14.  
  15. //Base case
  16. pascal[1][1] = 1;
  17.  
  18. for (int i=0; i<=n; i++) {
  19. for (int j=0; j<=n; j++) {
  20. pascal[i][j] = 0;
  21. }
  22. }
  23.  
  24. for (int i=1; i<=n; i++) {
  25. for (int j=1; j<=i; j++) {
  26. // first and last binomial coefficients are
  27. // always 1
  28. if (i == 1 || j == i) {
  29. pascal[i][j] = 1;
  30. } else {
  31. pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j];
  32. }
  33. }
  34. }
  35.  
  36. for (int i=1; i<=n; i++) {
  37. for (int j=1; j<=i; j++) {
  38. cout<<pascal[i][j]<<" ";
  39. }
  40. cout<<endl;
  41. }
  42.  
  43. }
  44.  
  45. int main() {
  46. int n = 7;
  47. printPascalTriangle (n);
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0.01s 5616KB
stdin
Standard input is empty
stdout
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 
1 6 15 20 15 6 1