For k = 4 I need to add the highlighted elements.If user enters k = 4 then the first element will be in the fourth row , second element in third row and so on.
k=0| 1
k=1| 1 1 -----> fourth from here
k=2| 1 2 1 -----> third from here
k=3| 1 3 3 1 -----> second element from here
k=4| 1 4 6 4 1 -----> first element from this row ,how do I add all these elements The code for Pascal's triangle is
#include<iostream>
using namespace std;
int main()
{
int pascal = 1;
int rows, columns;
cout << "Enter the number of rows : ";
cin >> rows;
cout << endl;
int **array = new int *[rows]; //generating array
for (int i = 0; i <= rows; i++)
array[i] = new int[columns];
for (int i = 0; i < rows; i++) // cycle to show pascal's triangle
{
int val = 1;
for (int j = 1; j < (rows - i); j++)
{
cout << " ";
}
for (int k = 0; k <= i; k++)
{
cout << " " << val;
val = val * (i - k) / (k + 1);
}
cout << endl;
}
cout << endl;
int k, sum;
cout << "Enter the value k: ";
cin >> k;
for (int i = 0; i <= rows; i++) { //cycle to calculate `kth` `fibonacci number`
for (int j = 0; j <= i; j++) {
if (j == 0 || i == 0) {
pascal = 1;
}
else {
pascal = pascal *(i - j + 1) / j;
}
array[i][j] = pascal;
sum = sum + array[k - i][i]; //trying to sum the diagonal elements
}
cout << "\n";
}
cout << sum;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire