I tried to implement it recursively (iteratively seemed less elegant, but please do correct me if I am wrong).But the output seems to be giving me trailing zeroes and the first few rows are unexpected.I have checked the base cases and the recursive cases , but they seem to be all right.The problem is definitely within the function.
#include <iostream>
unsigned long long p[1005][1005];
void pascal(int n)
{
if (n == 1)
{
p[0][0] = 1;
return;
}
else if (n == 2)
{
p[0][0] = 1; p[0][1] = 1;
return;
}
p[n][0] = 1;
p[n][n-1] = 1;
pascal(n-1);
for (int i = 1; i < n;++i)
{
p[n][i] = p[n-1][i-1] + p[n-1][i];
}
return;
}
int main()
{
int n;
std::cin >> n;
pascal(n);
for (int i = 0 ; i < n ; ++i)
{
for (int j = 0 ;j < i+1 ; ++j)
{
std::cout << p[i][j] << " ";
}
std::cout << "\n";
}
}
Output: (I enter)15
1
0 0
0 0 0
1 0 0 0
1 1 0 0 0
1 2 1 0 0 0
1 3 3 1 0 0 0
1 4 6 4 1 0 0 0
1 5 10 10 5 1 0 0 0
1 6 15 20 15 6 1 0 0 0
1 7 21 35 35 21 7 1 0 0 0
1 8 28 56 70 56 28 8 1 0 0 0
1 9 36 84 126 126 84 36 9 1 0 0 0
1 10 45 120 210 252 210 120 45 10 1 0 0 0
1 11 55 165 330 462 462 330 165 55 11 1 0 0 0