Accessing a row in Pascal's triangle?

422 views c++
2

Below in the code for pascal's triangle , which is not in a pyramid form because I just need the elements . After entering the number of rows and number 'n' , I need to take the nth row and then find its integrals . The question is how can I access the nth row to do some operations on it?
1
1 1
1 2 1
1 3 3 1------> If I want to access this row, how do I access it ?
1 4 6 4 1

Code

#include <iostream>

using namespace std;

int main(){

int pascal, rows, columns;

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;
            cout << "  " << pascal;
        }
        cout << endl;
    }
}
return 0;
}

answered question

Before you can access any row of the result you'd need to store it somewhere, rather than just printing it. Or know the n up front, so that when you get to it you can do your calculation in addition to printing.

Okay , So how do I store the nth row? @Jesper Juhl

1 Answer

9

You could simply store each row into a std::vector<int>, then keep a list of rows in a std::vector<std::vector<int>>. Then, to access the nth row after calculating the triangle, you just grab the nth element of the second vector.

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories