dimanche 4 novembre 2018

how to add the diagonal elements in an array?

Lets suppose I have an array given below . Now i want to add elements as mentioned below . How do I add them . If user enter 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

int k;
cout << "Enter the value k: ";
cin >> k;
for (int i = 0; i <= rows; i++) {  
    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; 
    }
    cout << "\n";
}

So how do I access the elements diagonally in order to add them and find the required fibonacci number. If k = 4 how do I add the diagonal elements for K = 4 or any other k.

Aucun commentaire:

Enregistrer un commentaire