patterncppMinor
Pascal's triangle using C++ vectors
Viewed 0 times
pascalvectorsusingtriangle
Problem
This is my C++ program. I wanted to print out Pascal's triangle. I let the user decide how many rows to print out. The first row is considered as 0, and is just:
1
I'm using vectors for this task. I think that I do not have to store the full triangle as that would take up too much extra space. I just store the previous row and the next one. I use the
1
I'm using vectors for this task. I think that I do not have to store the full triangle as that would take up too much extra space. I just store the previous row and the next one. I use the
SetRow() function to determine the numbers in the next row based on the numbers in the previous row. Then each row is printed out. Please give me some feedback on my code. Is it an effective way to approach this problem? Does my code have any "bad programming practices"? What would you have done differently?#include
#include
using std::vector;
using std::cout;
using std::cin;
using std::endl;
void SetRow(vector &old_row, vector &new_row, int row);
int main() {
int n_num;
cout > n_num;
cout row_1 = {1};
vector row_2;
vector curr_row;
cout &old_row, vector &new_row, int row) {
new_row.clear();
new_row.push_back(1);
for (int i = 0; i < (row - 1); i++) {
new_row.push_back(old_row.at(i) + old_row.at(i + 1));
}
new_row.push_back(1);
}Solution
The code seems all right; you might add the uniform variable initialization:
Then
Second off: why do you have the line
int n_num {};. Furthermore, the way you read the number of rows is unstable, when you use std::cin to do it. Imagine you enter "b" instead of a number. Your program has no loop, that prevents that. You could use a function that only reads integers:int readInt(std::istream& stream) {
/*
* Function to get integers, that are entered by the user
*/
int input;
stream >> input;
return input;
}Then
int num_n {readInt(std::cin)}; would be a possible way to do it.Second off: why do you have the line
else if (i % 2 == 0) ? I suppose you could just use else instead. If i % 2 == 1 returns false, it has to be 0. So there is no need to check again. It's like checking if your number is odd, and if it's not checking again if it's even.Code Snippets
int readInt(std::istream& stream) {
/*
* Function to get integers, that are entered by the user
*/
int input;
stream >> input;
return input;
}Context
StackExchange Code Review Q#156415, answer score: 3
Revisions (0)
No revisions yet.