well the question was:
"can u give me the code for this output:"
so i thought i give him the code and if he posts any questions ill try to explain.
but your right, a little explanation right away wouldnt hurt me, so here we go:
i think everything till line 18 is no big deal. when you want the exact output of your example, you would enter 5.
i think the hardest part here is to get
setw(depth - i) and b < ((i * 2) +1)
so ill explain how i got these. i think the implementation should be easy to understand after that.
with depth and the knowing about how the triangle is build we can get a lot of usefull values (exactly every value we need to print it ;) )
depth: the number of rows, entered
nos: number of stars in a row (thats what i called b in the code),
rownumber (i) * 2 + 1 (since we go with 1, 3, 5, 7, 9 etc and started with i = 0)
maxwidth of a row (the nos of the last row) is
(depth - 1) * 2 + 1
, because we started with i = 0, the max i can be i = depth - 1
the last thing we need is the number of blanks/spaces before we start printing the * in the rows.
since we know the nos and maxwidth, the number of blanks is:
1 2 3 4 5
|
nob = (maxwidth - nos) / 2
= (((depth -1) * 2 + 1) - (i * 2 + 1)) / 2
= (2depth - 2 +1 - 2i - 1) / 2
= (2depth - 2i - 2) / 2
= (depth - i - 1)
|
you may wonder why i have setw(depth - i) in the code, well thats just because i think it doesnt look good, when the triangle hits the edge(?) of the shell. so by not using "-1" i just shifted the whole thing 1 position to the right.
if that confuses you, im sorry. just use setw(depth - i - 1) if you want to implement the fomula 1 by 1. ;-)
when you understand this calculations i think its easy to understand the code.