/* This is the exact same as pascal.cpp, except at the end, I make a copy and negate all elements. There's nothing really exciting, except I want you to see how easy it is to make copies of potentially very large data structures. */ #include #include #include #include using namespace std; int main(int argc, char **argv) { int r; // The number of rows vector < vector > pascal; // The vector of vectors that holds Pascal's triangle vector < vector > negative_pascal; // This will be a copy, and we negate the elements. size_t i, j; istringstream ss; /* Error check the command line. */ if (argc != 2) { cerr << "usage: pascal rows\n"; return 1; } ss.clear(); ss.str(argv[1]); if (!(ss >> r)) { cerr << "Bad rows\n"; return 1; } /* Create an entry in the vector for each row. Then add values to each row by using push_back() with either the value one, or the sum of two values on the previous row. */ pascal.resize(r); for (i = 0; i < pascal.size(); i++) { for (j = 0; j <= i; j++) { if (j == 0 || j == i) { pascal[i].push_back(1); } else { pascal[i].push_back(pascal[i-1][j-1] + pascal[i-1][j]); } } } /* Make a copy of pascal. */ negative_pascal = pascal; /* Set each element of this to its negation. */ for (i = 0; i < negative_pascal.size(); i++) { for (j = 0; j < negative_pascal[i].size(); j++) { negative_pascal[i][j] = -negative_pascal[i][j]; } } /* Print both of them. */ printf("Pascal's Triangle:\n\n"); for (i = 0; i < pascal.size(); i++) { for (j = 0; j < pascal[i].size(); j++) printf(" %4d", pascal[i][j]); cout << endl; } printf("\nPascal's Negative Triangle:\n\n"); for (i = 0; i < negative_pascal.size(); i++) { for (j = 0; j < negative_pascal[i].size(); j++) printf(" %4d", negative_pascal[i][j]); cout << endl; } return 0; }