So close to getting the right output! For loops?
Mar 4, 2014 at 7:10am UTC
My goal is to take in an input height of h in [1,7] and output a diagonal matrix of 1's with the height h in a 7x7 matrix of zeros.
e.g.
For h = 5, the output should be:
1 0 0 0 0 0 0
1 1 0 0 0 0 0
1 1 1 0 0 0 0
1 1 1 1 0 0 0
1 1 1 1 1 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
My output is so close to the triangle of 1's, but it keeps adding one extra row of 1's underneath without the first 0 being a 1. For instance, when I run it for h = 5, I'll get:
1 0 0 0 0 0 0
1 1 0 0 0 0 0
1 1 1 0 0 0 0
1 1 1 1 0 0 0
1 1 1 1 1 0 0
0 1 1 1 1 0 0
0 0 0 0 0 0 0
I would really appreciate any help I can get on how to rid that last row of 1's!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <iostream>
#include <cstdlib>
#include <vector>
using std::vector;
int main(int argc, char ** argv){
if (argc < 2){
std::cout<< "Please input a height for the triangle \n" ;
}
int h = atoi(argv[1]);
vector<vector<int > > v(7, vector<int >(7,0));
int j = 0;
for (int i = 0; i < h; i++){
v[j][i] = 1;
j=i;
for (j; j < h; j++){
v[j][i] = 1;
}
}
for (int i = 0; i< v.size(); i++){
vector<int > row = v.at(i);
for (int j = 0; j < row.size(); j++){
std::cout<<row.at(j)<<'\t' ;
}
std::cout<<'\n' ;
}
return 0;
}
Mar 4, 2014 at 7:22am UTC
Remove line 21.
Mar 4, 2014 at 7:24am UTC
Haha, oh my. I feel silly.
Thank you so much! :D
Topic archived. No new replies allowed.